Here we will learn ng-init directive in angularjs with the example, how to use the ng-init directive in angulajs with example and use ng-init with multiple values in angularjs with example.
The ng-init
directive in angularjs is used to initialize application data during the starting of application. Generally in angularjs application ng-init directive is used to define a local variable with value and we can use that variable value in application wherever we required.
Following is the syntax of using ng-init
directive in angularjs.
<div ng-app="" ng-init="val1=hi">
---your code---
</div>
We will see how to use ng-init
directive in angularjs with simple example for that create new page in your application and write the code like as shown below.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
AngularJs ng-init Directive example
</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div ng-app="" ng-init="name='Tutlane'">
<p>Website Name: {{name}}</p>
</div>
</body>
</html>
If you observe above code we defined variable name and using that variable to display it on page when we run above code we will get output like as shown below
Following is the result of using angularjs ng-init directive example
We will learn how to declare multiple values with ng-init directive in angularjs application.
Following is the syntax of using multiple values with ng-init
directive in angularjs applications.
<div ng-app="" ng-init="val1=’hi’;val2=’hello’">
---your code---
</div>
Check following example to use ng-init
directive in angularjs application with multiple values.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
AngularJs ng-init Directive with Multiple Values example
</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div ng-app="" ng-init="msg1='Hi';msg2='Welcome to Tutlane Website'">
<p>{{msg1}}, {{msg2}}</p>
</div>
</body>
</html>
When we execute the above code we will get the result as shown below
Following is the result of using ng-init
directive in angularjs applications with multiple values
This is how we can use ng-init
directive in angularjs application with single value or multiple values.