What is ng-include

ng-include directive is used to add external html files into application. This directive helps us to create common page of website. Internally tis feature is using JavaScript Ajax to load another page in homepage.

To run this page, use a localhost or local server. Default protocol of html file is file:// and Ajax Request will not run without HTTP/HTTPS protocols. You can also open your angular project in Brackets Editor and use live previes feature. This will open your index.html file on 127.0.0.0 with HTTP Protocol.


ng-include example

Let’s say we are having html static website of 100 pages. We have common header menu and footer menu. So we have copy paste it in all 100 page. And in future if we need to modify the menu then we have to do it in all 100 pages which is quite difficult.

But ng-include directive helps to add html page dynamically into application. We can create separate html page for both header and footer. And we can include this with the help of ng-include.

Create a html file for header menu

		
//nav.html
<div>
<a href="home.html">Home</a> |
<a href="about.html">About us</a> |
<a href="contact.html">contact</a>|
<a href="login.html">Login</a>
</div>
		
		

Now create home.html to include this header page

		
		//Home.html
<!DOCTYPE html>
<html lang="en">
<head>
    <title>AngularJS ng-include example</title>
    <meta charset="UTF-8">
    <script src="angular.min.js"></script>
</head>
<body data-ng-app>
    <nav id="headermenu" data-ng-include="'nav.html'"></nav>
    <div>This is home page dummy content</div>
</body>
</html>

Now execute this code and you will see nav.html content will be added in home.html

		
		what is ng-include
		Figure 1
		
		

In my next article we will see more example of ng-repeat with ng-init.