ng-init directive example in AngularJS

Last Reply 6 months ago By dharmendr

Posted 6 months ago

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

Posted 6 months 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.

https://www.w3schools.com/angular/ng_ng-init.asp

https://docs.angularjs.org/api/ng/directive/ngInit

Syntax

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

Example

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>ng-init directive example</title>
</head>
<body>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', []);
    </script>
    <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>.
    </div>
</body>
</html>

Demo