Routing (ngRoute)
Configure routes with templates, controllers, and resolve guards.
Code
angular.module('routingApp', ['ngRoute'])
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeController',
controllerAs: 'vm'
})
.when('/user/:id', {
templateUrl: 'views/user.html',
controller: 'UserController',
controllerAs: 'vm',
resolve: {
user: function($route, UserService) {
return UserService.get($route.current.params.id);
}
}
})
.otherwise({ redirectTo: '/' });
$locationProvider.html5Mode(true);
})
.controller('UserController', function(user) {
this.user = user; // injected from resolve
});
<!-- Layout: <div ng-view></div> -->
<!-- Requires: angular-route.js -->Explanation
ngRoute (from the angular-route module) maps URL paths to template+controller pairs via $routeProvider.when; :id segments become $route.current.params. The resolve map pre-loads data before the controller instantiates, injecting each resolved value by name. html5Mode(true) removes the # from URLs but requires server-side rewrite support.
More AngularJS Snippets
Module & Controller
Define a module and a controller with scope methods.
Scope Inheritance
Prototypal scope inheritance between parent and child controllers.
Custom Directives
Attribute directive and element directive with isolated scope.
Services & Factories
Factory and service singletons for shared state and logic.
Custom Filters
Chainable filters for formatting values in templates.
Forms & Validation
Form with required, minlength, email validation, and disabled submit.