uncategorized

AngularJS: Change Page Title Based on Routers Dynamically

Ohhh… I find a problem that the pages do not have titles(just display as URL), when I play the demo in AngularJS Start with Yeoman, Grunt and Bower.

###Intuitively, the page title should be changed dynamically with routers’ changing.

I get my solution in this stackoverflow page.

You can find my repository in GitHub: AngularJS-Demo-Code

1. Open app/index.html:

1
<title ng-bind="title"></title>

Note: why use ng-bind?

1
2
3
// from https://coderwall.com/p/vcfo4q
It is preferrable to use ngBind instead of {{ expression }} when a template is
momentarily displayed by the browser in its raw state before Angular compiles it.

2. Change app.js as below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
'use strict';

/**
* @ngdoc overview
* @name angularJsDemoCodeApp
* @description
* # angularJsDemoCodeApp
*
* Main module of the application.
*/
var myApp = angular.module('angularJsDemoCodeApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'LocalStorageModule'
]);

myApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
title: 'Home Page',
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/about', {
title: 'About Page', // define title property for each controller
templateUrl: 'views/about.html',
controller: 'AboutCtrl'
})
.when('/todo', {
title: 'List Page',
templateUrl: 'views/todo.html',
controller: 'TodoCtrl'
})
.otherwise({
redirectTo: '/'
});
});

// change Page Title based on the routers
myApp.run(['$location', '$rootScope', function($location, $rootScope) {
$rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
$rootScope.title = current.$$route.title;
});
}]);

That’s all! :-)