Search code examples
angularjsroutespage-title

Set page title dynamically, use information from scope


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?


Solution

  • 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);
    });