From the other examples I found online I thought it would be easy to start using ng-include in angularJS to pull in bits of HTML from other files, but after hours of struggle spread out over several days I found it was not.
Let me correct that. It IS easy to do, you just have to be aware of some very important details.
- If you are attempting to do this on your local file system it will probably fail. The example I have below is syntactically correct, but as of this writing in November of 2014 it only works on Firefox. If you are using Chrome or IE you will only see the value of 3 in your output, not the contents of the included file. I put the {{ 1 + 2 }} in the html to show that Angular was working, even when the ng-include is not.
- If you move your files into a hosted web server and access them through the web server they probably will work.
- But if you use IE and your browser uses compatibility mode to view the web server you are hosting the files on, it still does not work. I think this is because Angular doesn’t support pre-IE8 browsers and compatibility mode is essentially rendering as IE7.
Here is the working code from my two files:
I name this file mypage.html
<!doctype html> <html> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script> </head> <body ng-app> {{ 1 + 2 }} <div ng-include="'myinclude.html'"></div> </body> </html>
Please be aware that you should surround your include name with single quotes which are encased in double quotes.
I name this file myinclude.html
My include is Showing!!!