AngularJS Routing using ngRoute Defining custom behavior for individual routes


Example

The simplest manner of defining custom behavior for individual routes would be fairly easy.

In this example we use it to authenticate a user :

1) routes.js: create a new property (like requireAuth) for any desired route

angular.module('yourApp').config(['$routeProvider', function($routeProvider) {
    $routeProvider
        .when('/home', {
            templateUrl: 'templates/home.html',
            requireAuth: true
        })
        .when('/login', {
            templateUrl: 'templates/login.html',
        })
        .otherwise({
            redirectTo: '/home'
        });
}])

2) In a top-tier controller that isn't bound to an element inside the ng-view (to avoid conflict with angular $routeProvider), check if the newUrl has the requireAuth property and act accordingly

angular.module('YourApp').controller('YourController', ['$scope', 'session', '$location',
    function($scope, session, $location) {

        $scope.$on('$routeChangeStart', function(angularEvent, newUrl) {
            
            if (newUrl.requireAuth && !session.user) {
                // User isn’t authenticated
                $location.path("/login");
            }
            
        });
    }
]);