ng-init Directive in AngularJS

In this post we will study ng-init directive in angular JS. This directive initializes application data. Let us see this with the help of an example.

Write the following HTML mark up in the webpage.

  1. <!doctype html>  
  2. <html ng-app>  
  3.   <head>  
  4.     <title>My Angular App</title>  
  5.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>  
  6.   </head>  
  7.   <body>  
  8. <div ng-app="" ng-init="Name='Nitin Tyagi'">  
  9. <p> You wrote: <span ng-bind="Name"></span>  </p>  
  10. </div>  
  11.   </body>  
  12. </html>  
In the preceding example we have assosciated Name variable to ng-init directive. Now we will assign the Name variable to the span using ng-bind directive. Doing this will make text appear in the span.

Let us run the page now.

output
We get the value of the variable in the span. Let us try one more example on the ng-init variable.

Write the following HTML code in the page.
  1. <!doctype html>  
  2. <html ng-app>  
  3.   <head>  
  4.     <title>My Angular App</title>  
  5.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>  
  6.   </head>  
  7.   <body>  
  8. <div ng-app="" ng-init="number1=20; number2=30">  
  9. Number 1: <input type="number" ng-model="number1">  
  10. Number 2: <input type="number" ng-model="number2">  
  11. Result: {{ number1 * number2 }}  
  12.   
  13. </div>  
  14. </body>  
  15. </html>  
In the ng-init directive we have taken two numbers i.e., number1 and number2 and initialized them to 20 and 30 respectively.

We take two input textbox which will take values from the ng-init directive.ng-model directive is used to bind the value to the textbox.Now using angular JS expressions {{ }} we will calculate the product of these numbers.

Let us run the form now and check the output.

output
We get the product of the two numbers using ng-init directive. This is how we use ng-init directive in angular js.

 

Ebook Download
View all
Learn
View all