30

I am using the following code to display page titles for each of my AngularJS app template, but whenever I try to enter an invalid URL to test the .otherwise I get the following error:

TypeError: Cannot read property 'title' of undefined
    at http://localhost/app/js/app.js:34:43

Below is the app.js, index.html code used:

app.js:

var myApp = angular.module('myApp', ['ngRoute', 'ngSanitize']);
myApp.config(['$routeProvider', function($routeProvider) {

       $routeProvider.when('/home', 
                {     templateUrl: 'templates/index.html', 
                      controller: 'MainController',
                      title: 'Welcome to Home Page'
                });
        $routeProvider.otherwise({
                                    redirectTo: '/home'

                                 });

}]);


myApp.run(['$location', '$rootScope', function($location, $rootScope) {
    $rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
        $rootScope.title = current.$$route.title;
    });
}]);

Index.html:

<title ng-bind="title +' - MyAPP Home'"> - MyApp</title>

Please suggest

Graham
  • 7,431
  • 18
  • 59
  • 84
Ammar Khan
  • 2,565
  • 6
  • 35
  • 60

1 Answers1

32

The $routeChangeSuccess event will be triggered no matter what, so avoid the error by testing the existence of the route:

myApp.run(['$location', '$rootScope', function($location, $rootScope) {
    $rootScope.$on('$routeChangeSuccess', function (event, current, previous) {

        if (current.hasOwnProperty('$$route')) {

            $rootScope.title = current.$$route.title;
        }
    });
}]);
Rohit Suthar
  • 3,528
  • 1
  • 42
  • 48
xxxnoisyxxx
  • 446
  • 4
  • 5