I need to dynamically load the page title using angular. What is the best way of doing this? Any ideas could be very useful.
Asked
Active
Viewed 224 times
2 Answers
0
It would be quite easy if you are defining your controller at the body level. If thats the case you can declare and define a scope variable like pageTitle and use it to show the page title. like this
If not, and if you are using routes to select controller based on the routes you could still do this using the rootScope like hows its shown here.
var myApp = angular.module('myApp', ['ngResource'])
myApp.config(
['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
title: 'Home',
templateUrl: '/Assets/Views/Home.html',
controller: 'HomeController'
});
$routeProvider.when('/Product/:id', {
title: 'Product',
templateUrl: '/Assets/Views/Product.html',
controller: 'ProductController'
});
}]);
myApp.run(['$location', '$rootScope', function($location, $rootScope) {
$rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
$rootScope.title = current.$$route.title;
});
}]);
HTML:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title ng-bind="'myApp — ' + title">myApp</title>
Edit :
This question on SO has very good answers and is similar to what your are looking for.

Community
- 1
- 1

Yasser Shaikh
- 46,934
- 46
- 204
- 281
0
<html ng-app="app" ng-controller="titleCtrl">
<head>
<title>{{ title }}</title>
...
Inside your controller
app.controller("titleCtrl",function($scope){
$scope.title="hello page";
});
Second way for different pages:-
You could define controller at the level.
<html ng-app="app" ng-controller="titleCtrl">
<head>
<title>{{ Page.title() }}</title>
...
You create service: Page and modify from controllers.
app.factory('Page', function() {
var title = 'default';
return {
title: function() { return title; },
setTitle: function(newTitle) { title = newTitle }
};
});
Inject Page and Call 'Page.setTitle()' from controllers.
for example:-
app.controller("pageonectrl",funtion($scope,Page){
Page.setTitle("pageone");
});
app.controller("pagetwoctrl",funtion($scope,Page){
Page.setTitle("pagetwo");
});
PS:-Second one is more efficient for practical purpose :)