ngRoute







Darryl Pogue
@dpogue
VanAngularJS - December 2013

Some Background Info









  • Back-end/Front-end Developer  at Ayogo Health

  • Experience with Ruby on Rails on the back-end

  • Started with AngularJS in April

  • Large application: lots of views, lots of controllers

If you don't have URLs in your webapp, it's no different than uploading an .exe to an FTP server somewhere — Tom Dale

ngRoute


  • An optional module (like ngTouch and ngAnimate)

  • It provides 3 things:
      • $routeProvider
      • $routeParams
      • ngView directive

  • You need to include it in your application:

angular.module('myApp', ['ngRoute'])

Creating a route


angular.module('myApp', ['ngRoute']).config(function($routeProvider) {
$routeProvider.when('/posts/:id', { controller: 'PostsCtrl', templateUrl: 'post.html' });
$routeProvider.otherwise({ redirectTo: '/posts/1' });
});

$routeProvider


  • You must specify a controller and a template or templateUrl if you are not redirecting.

  • You can specify "resolves", which are promises that must resolve before the route will be loaded.

  • There are some scope events around route changes:
      • $routeChangeStart
      • $routeChangeError
      • $routeChangeSuccess
      • $routeUpdate

Using RouteParams


angular.module('myApp').controller('PostsCtrl', function($scope, $routeParams) {
// We defined our route as "/posts/:id", so we have an 'id' // attribute on $routeParams. // For "/posts/1", $routeParams.id will be 1. $scope.post_id = $routeParams.id;
});

Showing the template


Use the ng-view directive:

<html>    <head>...</head>    <body>        <h1>My App</h1>
<div ng-view> </div>
</body></html>

Extra Features: Resolves

Provide a set of promises to be resolved before the route changes.
This means you can fetch data before running the controller and rendering the template.
angular.module('myApp', ['ngRoute','ngResource']).config(function($routeProvider) {    $routeProvider.when('/posts/', {        controller: 'PostsCtrl',        templateUrl: 'posts.html',        resolve: {            entry: function() {                return Entry.query().$promise;  // Using ngResource            }        }    });}).controller('PostsCtrl', function($scope, entry) {});

Questions?



These slides are available online:
http://slid.es/darrylpogue/vanangular-ng-route

vanangular-ng-route

By Darryl Pogue

vanangular-ng-route

ngRoute presentation for December 2013 VanAngularJS

  • 326