Saturday, 7 May 2016

Post 46: displaying a html module with ng-include

If you are writing AngularJS and want to use ng-include in order to display a html module within your page, for example this:

my-html-file.html:
<html ng-app="myAngularJSapp">
...
            <h3 ng-include="'product-title.html'"></h3>
...
</html>

my-module.html:
            <h1>{{product.name}}</h1>
            <h2>{{product.price | currency}}</h2>


Then you may notice this error message if you are loading your page with your file server:

angular.min.js:103 XMLHttpRequest cannot load file:///home/my-html-file.html. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.(anonymous function) @ angular.min.js:103
The reason why this happens is, that ng-include makes a XMLHttpRequest. If you're opening your page via your file server this XMLHttpRequest will not work because your localhost is not able to handle HTTP request.

Solution:
- run the code on a webserver
- Run a simple server with python -m SimpleHTTPServer
- install a simple server on your machine, e.g. https://github.com/devpaul/grunt-devserver 

Tweet