AngularJS Includes

There is a shortcoming of HTML. It doesn't have the functionality of embedding HTML pages within a HTML page. Thus, there are alternative methods in which this can be achieved. The two different ways are


Using Ajax

By using AJAX we can make a call to the server to obtain the corresponding HTML page and set it in the innerHTML of the HTML control.


Using Server Side Includes

Web side server technologies like JSP, PHP and are used to include HTML pages within a dynamic page.

For embedding HTML pages within a HTML page using AngularJS we can use the ng-include directive which is pretty simple. The ng-include directive is extremely useful when you want to include an external resource in an HTML template. If needed, you can also include only a fragment of a HTML template depending on a given specific condition.

The following code shows the implementation.

< body ng-app="">

<div ng-include="'myFile.htm'"></div>

</body>

What does the ng-include directive do?

The ng-include directive firstly fetches, then compiles and finally includes an external HTML fragment. The template URL and the application domain are restricted to the same domain and protocol. This can be done my making a call $sce.getTrustedResourceUrl on it. If you want to load templates from other domains and protocols, you have to either whitelist them or wrap them by considering them as trusted values.