Monday, January 13, 2014

AngularJS routing 101

Different ways to specify default routes in AngularJS (to fooCtrl in both examples) are:

  1. app.config(function($routeProvider) {
       $routeProvider
          .when('/', {
             controller: "fooCtrl",
             templateUrl: "templates/foo.html"
          })
          .when('/bar/:baz/:qux', {
             controller: "barCtrl",
             templateUrl: "templates/bar.html"
          });
          
  2. app.config(function($stateProvider, $urlRouterProvider) {
       $urlRouterProvider.otherwise("/foo");
       $stateProvider
          .state('foo', {
             url: "/foo",
             templateUrl: "templates/foo.html",
             controller: "fooCtrl"
          })
          .state('bar', {
             url: "/bar/:baz/:qux",
             templateUrl: "templates/bar.html",
             controller: 'barCtrl'
          });

 
 

I'm not yet sure how one fishes out the baz and qux variables in the first implemenation yet, but in the second implemenation, which I suspect is the more modern way to go, one would have $stateParams in the controller signature and then access the variables by doing a dot off of $stateParams like so:

ourControllers.controller('barCtrl', ['$scope', '$state', '$stateParams',
   function detailCtrl($scope, $state, $stateParams) {
      var baz = $stateParams.baz;
      var qux = $stateParams.qux;

 
 

The URL line should change up to reflect these routes. Also, you may just type in a route at the browser to jump to where you want to be. (This feature is called deep linking. AngularJS routing supports using the forward and back buttons on the browser too somehow. The buttons are adapted to allow for walking to the last route visited ahead or behind.)

No comments:

Post a Comment