The ng-init directive allows you to evaluate a expression in the current scope.
In the following example, the ng-init directive initializes employees variable which are then used in the Ng-repea T 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.
<!DOCTYPE HTML><HTMLxmlns= "http://www.w3.org/1999/xhtml"><Head> <title></title> <Scriptsrc= "Scripts/angular.min.js"></Script></Head><BodyNg-app> <DivNg-init= "Employees = [{name: ' Ben ', Gender: ' Male ', City: ' London '}, {name: ' Sara ', Gender: ' Female ', City: ' Chennai '}, {name: ' Mark ', Gender: ' Male ', City: ' Chicago '}, {name: ' Pam ', Gender: ' Female ', City: ' London '}, {name: ' Todd ', Gender: ' Male ', City: ' Chennai ' } ]"> <Table> <thead> <TR> <th>Name</th> <th>Gender</th> <th>City</th> </TR> </thead> <tbody> <TRng-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 is used for aliasing special properties of ng-repeat directive. In the following example, Ng-init are used to store the index of the parent element in Parentindex variable.
<!DOCTYPE HTML><HTMLxmlns= "http://www.w3.org/1999/xhtml"><Head> <title></title> <Scriptsrc= "Scripts/angular.min.js"></Script> <Scriptsrc= "Scripts/script.js"></Script></Head><BodyNg-app= "MyModule"> <DivNg-controller= "Mycontroller"> <ul> <binng-repeat= "Country in countries"Ng-init= "Parentindex = $index">{{Country.Name}}<ul> <Ling-repeat= "City in Country.cities">{{City.name}}-Parent index = {{Parentindex}}, index = {{$index}} </Li> </ul> </Li> </ul> </Div></Body></HTML>
script.js
varApp =angular. Module ("MyModule", []). Controller ("Mycontroller",function($scope) {varCountries =[{name:"India", cities: [{name:"Hyderabad"}, {name:"Chennai"}]}, {name:"USA", cities: [{name:"Los Angeles"}, {name:"Chicago" }, ] } ]; $scope. Countries=countries; });
Part AngularJS NG init directive