AngularJS ng-init directive:-

The ng-init directive allows you to evaluate an expression in the current scope. In the following example, the ng-init directive initializes employees variable which is then used in the ng-repeat directive to loop thru each employee. In a real world application you should use a controller instead of ng-init to initialize values on a scope.

Demo.html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="angular.min.js"></script> <style> body { font-family: Arial; } table { border-collapse: collapse; } td { border: 1px solid black; padding: 5px; } th { border: 1px solid black; padding: 5px; text-align: left; } </style> </head> <body ng-app> <div ng-init="employees = [ { name: 'Santosh Kumar Singh', gender: 'Male', city: 'Patna, Bihar' }, { name: 'Anu Singh', gender: 'Female', city: 'Utter Pradesh' }, { name: 'Rajeev Kumar', gender: 'Male', city: 'New Delhi' }, { name: 'Priyanka', gender: 'Female', city: 'Delhi' }, { name: 'Sanjay Kumar', gender: 'Male', city: 'Darbhanga' }, { name: 'Gagan', gender: 'Female', city: 'Haryana' }, { name: 'Chandan Kumar', gender: 'Male', city: 'Gaya' } ]"> <table> <thead> <tr> <th>Name</th> <th>Gender</th> <th>City</th> </tr> </thead> <tbody> <tr ng-repeat="employee in employees"> <td> {{ employee.name }} </td> <td> {{ employee.gender}} </td> <td> {{ employee.city}} </td> </tr> </tbody> </table> </div> </body> </html>


ng-init should only be used for aliasing special properties of ng-repeat directive. In the following example, ng-init is used to store the index of the parent element in parentIndex variable.

Demo1.html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="angular.min.js"></script> <script src="Demo.js"></script> </head> <body ng-app="myModule"> <div ng-controller="myController"> <ul> <li ng-repeat="country in countries" ng-init="parentIndex = $index"> {{country.name}} <ul> <li ng-repeat="city in country.cities"> {{city.name}} - Parent Index = {{ parentIndex }}, Index = {{ $index }} </li> </ul> </li> </ul> </div> </body> </html>


Demo.js
var app = angular .module("myModule", []) .controller("myController", function ($scope) { var countries = [ { name: "India", cities: [ { name: "Bihar" }, { name: "Utter Pradesh" }, { name: "New Delhi" } , { name: "Delhi" }, { name: "Darbhanga" }, { name: "Haryana" }, { name: "Gaya" } ] } ]; $scope.countries = countries; });