Sunday, 24 May 2015

Concept of Views

Today, lets know about Angular JS Views.

Angular JS supports Single Page Application via multiple views on a single page. To do this Angular JS has provided "ng-view" and "ng-template" directives and "$routeProvider" services.

ng-view tag simply creates a place holder where a corresponding view (html or ng-template view) can be placed based on the configuration.

ng-template directive is used to create an html view using script tag. It contains "id" attribute which is used by $routeProvider to map a view with a controller.

$routeProvider is the key service which set the configuration of urls, map them with the
corresponding html page or ng-template, and attach a controller with the same.

Let me show you a small example.

main.html:-
<html>
<head>
<title>Angular JS Views</title>
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="mainApp">
<p><a href="#addStudent">Add Student</a></p>
<p><a href="#viewStudents">View Students</a></p>
<div ng-view></div>
<script type="text/ng-template" id="addStudent.htm">
<h2> Add Student </h2>
{{message}}
</script>
<script type="text/ng-template" id="viewStudents.htm">
<h2> View Students </h2>
{{message}}
</script>
</div>
<script src="app.js"></script>
<script src="addstudent.js"></script>
<script src="viewstudent.js"></script>
</body>
</html>


addstudent.js:-
mainApp.controller('AddStudentController', function($scope) {
$scope.message = "This page will be used to display add student form";
});


viewstudent.js:-
mainApp.controller('ViewStudentsController', function($scope) {
$scope.message = "This page will be used to display all the students";
});


app.js:-
var mainApp = angular.module("mainApp", ['ngRoute']);
mainApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/addStudent', {
templateUrl: 'addStudent.htm',
controller: 'AddStudentController'
}).
when('/viewStudents', {
templateUrl: 'viewStudents.htm',
controller: 'ViewStudentsController'
}).
otherwise({
redirectTo: '/addStudent'
});
}]);


Screenshots:-





Explanation:-

$routeProvider is defined as a function under config of mainApp module using key as "$routeProvider".

$routeProvider, when defines a url "/addStudent" which then is mapped to "addStudent.htm".  addStudent.htm should be present in the same path as main html page. If html page is not defined then "ng-template" to be used with id="addStudent.htm". I have used ng-template.

"otherwise" is used to set the default view. "controller" is used to set the corresponding controller for the view.

No comments:

Post a Comment