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.

ng-init example

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



<body data-ng-app >
<body ng-app >
<div data-ng-init="name='isha'; empid=102 ">


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>
<html lang="en">
    <title>Angular JS</title>
    <meta charset="UTF-8">
    <script src="angular.js"></script>
    var x=angular.module("m1",[]);
<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>Id is {{x.id}}</p>
        <p>Name is {{x.name}}</p>

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

		ng-init with ng-repeat
		Figure 2