Is it possible to use ng-include without web server?

二次信任 提交于 2019-12-17 08:54:07

问题


I'm running an AngularJS app which merely include a file

<div ng-include src="'sample.html'"></div>

That works when run under web server. But if the web app is run from merely double clicking from file explorer (i.e. not from web server), it doesn't include the file

Does ng-include works outside of web server? I checked the Network status on Chrome, it says OPTIONS on Method, and Load cancelled on Status


回答1:


One workaround is to inline your templates:

<script type="text/ng-template" id="sample.html">
  <div>This is my sample template</div>
</script>

Fiddle.

This puts your template into Angular's template cache. When an ng-include directive is processed, Angular checks the cache first.




回答2:


The problem is because of file:// protocol. Mostly all browsers disallow XHR requests when file is been served from file://. That is why AJAX requests are failing. And ng-include use them to download files.

You can launch Chrome with --allow-file-access-from-files parameter to disable checks for file://.

FireFox should load files if they are in same folder (check this for more info).

But personally prefer to start simplest NodeJS script to serve files, that could be found at angular-seed project. It require just node binary and gives a feeling of a normal web server.




回答3:


I had a similar problem and I solved it by running a simple nodejs server to serve static files - http-server. Make sure you have nodejs installed, then:

Install:

$ sudo npm install http-server -g

Then from your project directory:

$ http-server

Now you can access your files from:

localhost:8080/whatever-file-you-have-in-your-directory.html




回答4:


You can use Grunt along with the grunt-html plug to precompile your templates along with your Angular code.




回答5:


Using virtual Host on your xampp is the best solution , and give custom name like yourProject.dev

update httpd-vhosts file in C:\xampp\apache\conf\extra\httpd-vhosts

<VirtualHost *:80>
        ServerName  yourProject.dev
        ServerAlias www.yourProject.dev  yourProject.com www.yourProject.com
        DocumentRoot "C:\Users\customFolder/yourProject"
        <Directory "C:\Users\customFolder/yourProject">
            DirectoryIndex index.html index.php
            ServerSignature Off
            Options Indexes FollowSymLinks IncludesNoExec
            AllowOverride All
            Allow from all
            Require all granted
      </Directory>
</VirtualHost>

then update your hosts file to 127.0.0.1 yourProject.dev

in Windows : c:\Windows\System32\Drivers\etc\hosts

in Mac : /private/etc/hosts

don't forget to rest your xampp/wampp



来源:https://stackoverflow.com/questions/14420337/is-it-possible-to-use-ng-include-without-web-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!