Skip to content

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)


<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.


<body data-ng-app >
<body ng-app >
<div data-ng-init="name='Anand';score=45">

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.

See also  How to crop images in CSS

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.