1

I would like to set page titles in AngularJS dynamically per route, and the solution in https://stackoverflow.com/a/13407227/353337 has served me well. Now, instead of having the page title say "Article", I would like to display the actual title of the article, i.e., I'd like to use information from the current scope.

How would this be possible?

Community
  • 1
  • 1
Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249
  • 2
    On the same question you link, look at this answer instead: http://stackoverflow.com/a/17898250/4555964. And I would incorporate the comment by Kristo Aun on this answer about using routeChangeStart instead of routeChangeSuccess for setting the default. – Matthew Jaspers Mar 25 '15 at 18:34

1 Answers1

1

The most flexible way of doing this is emitting an event from the controller.

Here's how to do it:

Index page (stays the same)

<html ng-app="app" ng-controller="RootCtrl">
    <title data-ng-bind="htmlTitle"></title>
    ...

Root app controller

angular.module('app').controller('RootCtrl', function(){
   $scope.$on('changedPage', function changedPage(event, pageTitle){
      $scope.htmlTitle = pageTitle;
   });
});

Any route controller

angular.module('app').controller('HomeCtrl', function(){
   var pageTitle = "Build this string however you want";
   $scope.$emit('changedPage', pageTitle);
});
Dan Mindru
  • 5,986
  • 4
  • 28
  • 42