How to use ng-include for reusable templates?

Loading

  • ng-include is an AngularJS directive that loads external HTML templates into a view.
  • It allows code reuse, making applications modular and maintainable.

1. Basic Usage of ng-include

Example: Including a Header File

Step 1: Create header.html (Reusable Template)

<div class="header">
<h1>Welcome to My Website</h1>
<p>This is the header section.</p>
</div>

Step 2: Use ng-include in index.html

<div ng-app="myApp">
<div ng-include="'header.html'"></div>
</div>

Explanation:

  • The header.html file is loaded into the <div> where ng-include is placed.

2. Using ng-include with a Scope Controller

Example: Dynamically Loading Templates

Step 1: Create AngularJS App

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

app.controller("MainController", function ($scope) {
$scope.templateURL = "header.html";
});

Step 2: Use ng-include Dynamically

<div ng-app="myApp" ng-controller="MainController">
<div ng-include="templateURL"></div>
</div>

Now, the template is dynamically assigned from $scope.templateURL.


3. Using ng-include Inside ng-repeat

ng-include can be used inside an ng-repeat loop to load multiple components dynamically.

Example: Repeating a Card Layout

Step 1: Create card.html (Reusable Template)

<div class="card">
<h3>{{ user.name }}</h3>
<p>Email: {{ user.email }}</p>
</div>

Step 2: Use ng-include in index.html

<div ng-app="myApp" ng-controller="UserController">
<div ng-repeat="user in users">
<div ng-include="'card.html'"></div>
</div>
</div>

Step 3: Define Controller in app.js

app.controller("UserController", function ($scope) {
$scope.users = [
{ name: "Alice", email: "alice@example.com" },
{ name: "Bob", email: "bob@example.com" },
];
});

Explanation:

  • Each user object is passed into card.html dynamically.
  • Avoids repeating code in multiple places.

4. Using ng-include with Conditional Loading

Example: Switching Between Templates

<div ng-app="myApp" ng-controller="MainController">
<button ng-click="templateURL='header.html'">Load Header</button>
<button ng-click="templateURL='footer.html'">Load Footer</button>

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

Now, clicking a button will change the included template dynamically.


Best Practices for Using ng-include

Use relative paths ('header.html') for templates.
Keep templates in a separate folder (e.g., /templates/header.html).
Ensure templates are loaded asynchronously (avoid blocking UI).
Use controllers to manage dynamic includes.

Leave a Reply

Your email address will not be published. Required fields are marked *