Code


<!DOCTYPE html> <html> <head> <script src="angular.js"></script> </head> <body ng-app ng-init="inputVar = 'test';"> <label>Type something: <input type="text" ng-model="inputVar" /></label><br /> <br /> <h3>1. Simple include</h3> <div ng-include="'fragment1.html'"></div> <br /> <h3>2. Conditional include</h3> <label>Include fragment 2: <input type="checkbox" ng-model="includeFrag2" /></label> <div ng-include="includeFrag2 ? 'fragment2.html' : 'fragment1.html'"></div> </div> </body> </html>
<div style="background-color: #fcfcfc; border: 1px solid #e1e1e1; text-align: center; width: 200px;"> Fragment 1: {{$parent.inputVar}} </div>
<div style="background-color: #fcfcfc; border: 1px solid #e1e1e1; text-align: center; width: 200px;"> Fragment 2: {{$parent.inputVar}} </div>

Example


Description


The ng-include directive is useful if we want to include an external resource in an HTML template. We could, for example, include a fragment of a HTML template depending on a specific condition.

In point 1 of the example we can see a straightforward case. We just include a fragment1.html partial template inside our main one and we use a div element as a container.

In point 2 we see that we can use a conditional expression with the ng-include directive to decide if we have to include fragment1.html or fragment2.html depending on the value of the includeFrag2 model variable.

The ng-include directive creates a new scope.

In both the points of the example, we see that we can use our AngularJS data binding normally, but we need to pay attention to the scope. Since the ng-include directive creates a new scope, we must refer to the $parent scope if we want to access the inputVar variable.