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'">


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'">
    <input type="text" ng-model="number">
    <p>Square is {{number*number}} </p>

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>
    <title>Untitled Document</title>
    <meta charset="UTF-8">
    <script src="angular.js"></script>
    var x=angular.module("m1",[]);
<body ng-app="m1">
<div ng-controller="con1">
    <div ng-repeat="x in employee">
        <p ng-init="index=$index">
      <b> Record No :- {{index+1}}</b> 
        Id is {{x.id}}
        Name is {{x.name}}


Now execute this code and you will get following output:-

		ng-init with ng-repeat
		Figure 2