ng-init directive example in AngularJS

Last Reply one year ago By dharmendr

Posted one year ago

When ng-init directive is used. Please give an example.

Posted one year ago

Hi rani,

The ng-init directive evaluates the given expression(s) in the current scope.

The ng-init directive can add some unnecessary logic into the scope, and you are recommended to do your evaluations in a controller instead.

There are only a few appropriate uses of ngInit:

Aliasing special properties of ngRepeat.

Initializing data during development.

Injecting data via server side scripting.

For more details refer below link.


<element ng-init="expression" ></element>


<html xmlns="">
    <title>ng-init directive example</title>
    <script type="text/javascript" src=""></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', []);
    <div ng-app="MyApp" ng-init="Number1=50;Number2=25">
        <p>Number 1 is <b>{{Number1}}.</b></p>
        <p>Number 2 is <b>{{Number2}}.</b></p>
        Sum of Number 1 and Number 2 is <b>{{Number1 + Number2}}</b>.