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
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;
}
});
}]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With