What 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.

Example of ng-init

In the following example, I have created ng-init, assign value in it, and simply print it.

		
<body ng-app ng-init="name='isha'">
<div>
    {{name}}
    </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

		
		example of ng-init
		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>
<head>
    <title>Untitled Document</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 ng-app="m1">
<div ng-controller="con1">
    <div ng-repeat="x in employee">
    <p>
        <p ng-init="index=$index">
      <b> Record No :- {{index+1}}</b> 
        </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:-

		
		ng-init with ng-repeat
		Figure 2