Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set page title with AngularJS [duplicate]

Tags:

angularjs

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

like image 265
Ammar Khan Avatar asked Mar 11 '14 12:03

Ammar Khan


1 Answers

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;
        }
    });
}]);
like image 133
xxxnoisyxxx Avatar answered Nov 05 '22 08:11

xxxnoisyxxx