Getting Started with AngularJS (pt 2): views and ngRoute

Second part of my notes learning AngularJS (first part is here).

Angular handles multiple views in your Single Page Application by adding the ng-view directive at the point where you want your views inserted, e.g.

<div ng-view></div>

The logic to handle URL hash fragments is implemented using $routeProvider to map view template and controller pairs with each hash fragment that your app recognizes. For example:

var simpleApp = angular.module('SimpleApp',
  [
    "ngRoute",
    "SimpleControllers"
  ]);

simpleApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
    when('/', {
      templateUrl: 'page1.html',
      controller: 'Page1Controller'
    }).
    when('/page2', {
      templateUrl: 'page2.html',
      controller: 'Page2Controller'
    }).
    when('/page3', {
      templateUrl: 'page3.html',
      controller: 'Page3Controller'
    }).
    otherwise({
      redirectTo: '/'
    });
  }]);

An example working app is here: https://github.com/kevinhooke/SimpleAngularJSExample-ngRoute

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.