In AngularJS, the ng-include
directive is used to include external HTML fragments (or templates) into an AngularJS application. It allows you to modularize your application by breaking it into smaller components or views and then including these components where needed.
The ng-include
directive can be used in various ways:
-
Including an External HTML File:
<div ng-include="'path/to/template.html'"></div>
This will load the content of
template.html
into theelement.- Using a Scope Variable:
You can also bind the file path to a scope variable:
<div ng-include="templatePath"></div>
In the controller:
$scope.templatePath = 'path/to/template.html';
- Loading Templates Conditionally:
ng-include
can be used withinng-if
or other conditional statements to load templates conditionally:<div ng-if="showTemplate" ng-include="'path/to/template.html'"></div>
Where
showTemplate
is a variable in the controller's scope.- Using Expressions:
You can also use expressions in
ng-include
to dynamically determine the template path:<div ng-include="'path/to/' + templateName + '.html'"></div>
Here,
templateName
is a variable in the scope.- Events and Re-evaluating
ng-include
:If the included content needs to change dynamically based on some event or condition change, you can re-evaluate the
ng-include
attribute value:<div ng-include="templatePath"></div> <button ng-click="changeTemplate()">Change Template</button>
$scope.templatePath = 'path/to/template1.html'; $scope.changeTemplate = function() { $scope.templatePath = 'path/to/template2.html'; };
Clicking the button will change the included template from
template1.html to template2.html
.ng-include
is a useful directive in AngularJS for modularizing and reusing HTML templates or components across an application. It helps in maintaining a more structured and manageable codebase by breaking down views into smaller, reusable components.Webnza Team
30th November, 2023
- Using a Scope Variable: