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.htmlinto 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-includecan be used withinng-ifor other conditional statements to load templates conditionally:<div ng-if="showTemplate" ng-include="'path/to/template.html'"></div>Where
showTemplateis a variable in the controller's scope.- Using Expressions:
You can also use expressions in
ng-includeto dynamically determine the template path:<div ng-include="'path/to/' + templateName + '.html'"></div>Here,
templateNameis 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-includeattribute 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-includeis 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: