AngularJS ng-init Directive with Example

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.

AngularJS ng-init Directive

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.

Syntax of AngularJS ng-init Directive

Following is the syntax of using ng-init directive in angularjs.

 

<div ng-app="" ng-init="val1=hi">

---your code---

</div>

AngularJS ng-init Directive Example

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.

 

Live Preview

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

Output of AngularJS ng-init Directive 

Following is the result of using angularjs ng-init directive example

 

Website Name: Tutlane

AngularJS ng-init Directive with Multiple Values

We will learn how to declare multiple values with ng-init directive in angularjs application.

Syntax to Declare Multiple Values with ng-init Directive

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>

Example of AngularJS ng-init with Multiple Values

Check following example to use ng-init directive in angularjs application with multiple values.

 

Live Preview

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

Output of ng-init with Multiple Values

Following is the result of using ng-init directive in angularjs applications with multiple values

 

Hi, Welcome to Tutlane Website

This is how we can use ng-init directive in angularjs application with single value or multiple values.