AngularJS ng-view Directive with Example

  Total Views : 861
  Comments : 0
 
  Keywords : What is ng-view directive in angularjs, How to use ng-view in angularjs applications with example, Use ng-view directive in angularjs to change views using route configurations with exmaple

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

AngularJS ng-view Directive

“ng-view” directive in angularjs is used to switch between views in angularJs application. Generally we will ng-view directive with route service to change views based on conditions in angular applications.

Syntax of ng-view Directive in AngularJS

Following is the syntax of using 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.

Example of AngularJS ng-view Directive

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 Directive

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 we can use ng-view directive in angularjs application. 

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User