Understanding routes

Routes play a very important role in your angularjs app. The routes essentially tell angularjs what controller and view to use for the given browser URL.

In our application, the routes are stored in the app/scripts/app.js file.

Routes make use of $routeProvider, and each route has two parameters: the first parameter is the path and the second is an object parameter. The following lines of code are entered under $routeProvider:

    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })

The when part defines the URL in the browser address bar. The templateURL part points to the partial that would be called within the ng-view directive. The controller part defines the controller function that will bind this view.

In angularjs, the views and controllers are loosely coupled. What this means is that controllers and views are independent of each other, and it is in the routes file that a controller is linked to the view. So, essentially, you could have two different views bound to a single controller. This improves code reusability.




After the completion of this Tutorial, your routes would look something like the following.

'use strict';

angular.module('hlApp', ['ui.bootstrap','ngGrid'])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .when('/articles', {
        templateUrl: 'views/articles.html',
        controller: 'ArticlesCtrl'
      })
      .when('/gallery', {
        templateUrl: 'views/gallery.html',
        controller: 'GalleryCtrl'
      })
      .when('/subscribers', {
        templateUrl: 'views/subscribers.html',
        controller: 'SubscribersCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  });

The 'use strict' command that you see at the start of most of our files is a new feature of ECMAScript 5, which makes the file or function operate in a strict context. You can read more about it at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode.