AngularJS ng-view Directive with Example

Here we will learn what is ng-view directive in angularjs and how to use the ng-view directive in angularjs applications with simple example.

AngularJS ng-view Directive

In angularjs, ng-view directive is used to switch between the views in angularJs application. Generally, we will use ng-view directive with route service to change the views based on the defined conditions in angular applications.

AngularJS ng-view Directive Syntax

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

 

<div ng-app="AngularngviewApp">

<ng-view></ng-view>

</div>

We will see how to use ng-view directive in angularjs application.

AngularJS ng-view Directive Example

To use ng-view directive in angularjs application first open your application and create new HTML page (sample1.html) and write the code like as shown below

 

<h1>{{model.text}}</h1>

Now create another html 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-view Directive Example

</title>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>

<script >

var myApp = angular.module("AngularngviewApp", ['ngRoute']);

myApp.config(['$routeProvider',

function ($routeProvider) {

$routeProvider.when('/', {

templateUrl: 'sample1.html',

controller: 'ngviewctrl'

})

}

]);

myApp.controller("ngviewctrl", function ($scope) {

$scope.model = {

text: "This is the example of ng-view in angular js"

}

});

</script>

</head>

<body ng-app="AngularngviewApp">

<div ng-controller="ngviewctrl">

<ng-view></ng-view>

</div>

</body>

</html>

If you observe above code we used route service to switch templates based on requirement. Here we are getting sample1.html page as template and binding that values to ng-view in controller "ngviewctrl". If we run above application we will get output like as shown below. 

Output of AngularJS ng-view Example

Following is the output of using ng-view directive in angularjs application example

 

This is the example of ng-view in angular js

This is how we can use ng-view directive in angularjs application.