AngularJS ng-init directive
In this post, we will learn about ng-init directive in Angular and its usages. ng-init is an Angular.js directive that helps in initializing data to a variable and evaluating expressions.
ng-init directive is used to initialize a variable, which will allows evaluating an expression in given scope.
(you can learn about ng-app directive here)
Syntax
<element ng-init="expression" ></element>
expression can be an assignment of value to a variable or it can evaluate to a value.
The examples below show how to use the ng-init directive in a simple way.
Examples
<body data-ng-app > <body ng-app > <div data-ng-init="name='Anand';score=45"> <p>{{name}}</p> <p>{{score}}</p> </div> </body>
In the above example, I just assign values to name and score and print them.
As per the official documentation, the ng-init
directive can add some unnecessary logic into the scope, and you are recommended to do your evaluations in a controller instead.