[email protected]      beta
Donate

AngularJs ng-init directives

Overview: Understanding ng-init directive, What is ng-init in angularjs, Use of AngularJS ng-init directives with an example, ng-init defines initial values for an angularjs application.

What is ng-init directives?

In angularjs, the ng-init directives define the initial values for an angularjs application. It means ng-init used to initialize application data and which will allow evaluating an expression in given scope.

In web application sometime we may require some local data for our application, so this can be done with the ng-init directive.

Usage of ng-init directive:

<div ng-app ng-init="message='hello world'">
     {{ message }}
</div>

Note: Using ng-init is not a good practice, we may use ng-controller instead of it.


Example of AngularJS ng-init directives

Example 1: Use ng-init with single value

Here in this example we are going to create a variable named as “message” using ng-init, and will display this variable text on the page load.

  • Add ng-init directive to the div tag.
  • Add a variable to ng-init, initialize some value to it.
  • Use angularjs express to display variable text on page load.

The code looks like as written below

<div ng-app ng-init="message='Hello World'">
     {{ message }}
</div>

Try is yourself

Output: Hello World

Using ng-init directive example 1 output


Example 2: Use ng-init with multiple & complex values.

Here in this example, we learn how to use ng-init with complex JSON data.

Here we are going to calculate an average score from mark-sheet using number expressions.

<div ng-app="" ng-init="minMarks=35;maxMarks=100; marks={physisc:90,chemistry:65,math:75,biology:80}">
   Total score {{ marks.physisc + marks.chemistry + marks.math + marks.biology}} out of {{ 4 * maxMarks}}
</div>

Try is yourself

Output:

Using ng-init directive  with complex JSON data example 2 output


  Popular Tag
  Recent Posts
  Follow Us
If you find these tutorials helpful then please donate. It will lead me to do more tutorials.
Donate