ng-init in angularjs
Written By:- Isha MalhotraWhat is ng-init
Ng-init directive is used to initialize a variable, which will allows evaluating an expression in given scope. According to angular official document, this directive is abused as it adds unnecessary business logic in the application. Still to evaluate an expression we required that directive.
ng-init example
In the following example, I have created ng-init, assign value in it, and simply print it.
isha
102
<body data-ng-app >
<body ng-app >
<div data-ng-init="name='isha'; empid=102 ">
<p>{{name}}</p>
<p>{{empid}}</p>
</div>
</body>
I have declared name in ng-init and assign value and simple print it in angular brackets. It will simply show this data.
We can also bind this ng-init variable in ng-model and can use it in application in the following manner:-
<body ng-app ng-init="number='5'">
<div>
<input type="text" ng-model="number">
<p>Square is {{number*number}} </p>
</div>
</body>
You will get following output
Figure 1
Another important use of ng-init is in ng-repeat. We can use ng-init to hold the $index in ng-repeat directives in the following manner:-
<!DOCTYPE html>
<html lang="en">
<head>
<title>Angular JS</title>
<meta charset="UTF-8">
<script src="angular.js"></script>
<script>
var x=angular.module("m1",[]);
x.controller("con1",function($scope){
$scope.employee=[
{id:101,name:'isha'},
{id:102,name:'neha'},
{id:103,name:'pooja'},
];
});
</script>
</head>
<body data-ng-app="m1">
<div data-ng-controller="con1">
<div data-ng-repeat="x in employee">
<p data-ng-init="index=$index">
<b> Record No :- {{index+1}}</b>
</p>
</p>Id is {{x.id}}</p>
<p>Name is {{x.name}}</p>
</div>
</div>
</body>
</html>
Now execute this code and you will get following output:-
Figure 2