Thursday 8 October 2015

Using ngView in AngularJS to create multiple page view.

AngularJS is one of the leading JavaScript framework which is doing something simply awesome. Whenever we talk about ngView we have to think about routeConfig which is actually making multiple page views possible. So with routeConfig we can embed a whole website into a single webpage. In this example we have not used multiple html page but rather used template to embed html document object into div block using ngView. So you can try this code to embed as many template you like based on the key parameter you provide on your url. Route Config use a angular function config which embed html block provided in the template with .when and if any of the parameter key does not match then goes to .otherwise where it automatically redirects it to a error page which displays an error message. Template of error key is also defined in .when.

<html ng-app="app">
<head>
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script>
app = angular.module('app',['ngRoute']);
app.controller('MyCtrl',function($scope) {
});
app.config(function($routeProvider) {
  $routeProvider
  .when('/', {
     template: '<h2>You are at the Welcome page</h2>',
     controller: 'MyCtrl' }
  )
  .when('/Documents',{
     template: '<h2>Read online tutorials</h2>',
     controller: 'MyCtrl' }
  )
  .when('/Downloads',{
     template: '<h2>Download utility software</h2>',
     controller: 'MyCtrl' }
  )
  .when('/error',{
     template : '<h2>Oops you have entered a wrong url',
     controller: 'MyCtrl' }
  )
  .otherwise( {
     redirectTo: '/error'
      }
  );
});
</script>
</head>
<body ng-controller="MyCtrl">
<div ng-view></div>
</body>
</html>

No comments: