AngularJS ng-include Directive with Example

Here we will learn ng-include directive in angularjs with the example, uses of ng-include directive in angularjs and how to use the ng-include directive in angularjs with example.

AngularJS ng-include Directive

In angularjs, the ng-include directive will compile and include one HTML page in another page. Since we know that embedding one HTML page in another HTML page is not supported in HTML to achieve this we need to follow some custom approaches like Ajax and including HTML via server-side programming.

 

In angularjs, we don't need to write any functionality to embed one external HTML into another HTML just by using “ng-include” directive we can achieve this functionality. The “ng-include” fetches, compiles and includes an external HTML fragment.

AngularJS ng-include Directive Syntax

Following is the syntax of using ng-include directive in angularjs applications.

 

<div ng-include src="path of your page"/>

If you observe above syntax we are calling URL of page which we need to include in src tag. We will see how to use ng-include directive in angularjs with a complete example.

AngularJS ng-include Directive Example

Now open your application and create new HTML page sample1.html and write the code like as shown below

 

<b>Sample1 Template Page</b>

Again create another page sample2.html and write the code like as shown below

 

<b>Sample2 Template Page</b>

Now create another html page (ngincludesample.html) and write the code like as shown below

 

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>

AngularJs ng-include Directive Example

</title>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<script>

var app = angular.module("AngularngincludeApp", []);

app.controller("ngincludectrl", function ($scope) {

$scope.items = ['--select--','sample1.html', 'sample2.html'];

$scope.selectval = "--select--";

});

</script>

</head>

<body ng-app="AngularngincludeApp">

<div ng-controller="ngincludectrl">

Select Item: <select ng-model="selectval" ng-options="item for item in items">

</select>

<br /><br />

<div style="border:1px solid #000; padding:10px; width:20%">

<div ng-include="selectval"></div>

</div>

</div>

</body>

</html>

 If you observe above code we are including our html pages sample1.html and sample2.html based on our dropdownlist selection values. Now run application that will return output like as shown below

Output of AngularJS ng-include Example

Following is the result of using ng-include directive in angularjs application.

 Angularjs ng-include Directive Example output or Result

This is how we can use ng-include directive in angularjs to embed or include external HTML files into another files.