简体   繁体   中英

How to manipulate the <title> of an AngularJS single page app?

I have a single-page AngularJS app. The index.html file looks like this:

<html ng-app="myApp" ng-controller="MyCtrl as myctrl">
  <head>
    <link rel="stylesheet" href="my-style-sheet.css">
    <title>{{myctrl.title}}</title>
  </head>
  <body>
    <div class="container">
      <ol>
        <li><a ui-sref="stateA">StateA</a></li>
        <li><a ui-sref="stateB">StateB</a></li>
      </ol>
      <div ui-view></div>
    </div>
    <script src="my-app.js"></script>
  </body>
</html>

As the user clicks on the StateA or StateB links, the page displays the content of those pages in place of <div ui-view></div> . Terrific.

As the user clicks around, the displayed content changes. I need the title of the page to change too. Currently it gets the title from the controller MyCtrl like this: <title>{{myctrl.title}}</title> . But when the user clicks those links, those states each have their own controllers. So I cannot use <title>{{myctrl.title}}</title> .

How can I update the title when various states the user clicks on have different controllers?

You can attach some data to each state of your routes, like a value that can be used to set the title of the page.

.state('test', {
    url: '/test',
    templateUrl: '/templates/test.html',
    data: {
        title: 'test title'
    }
})

Then write a directive to read the title. You can check to see if the required data is available on the state you are going to, and attach the whole thing to $stateChangeSuccess event.

function dynamicTitle($rootScope, $timeout) {
    return {
        link: function(scope, el) {
            $rootScope.$on('$stateChangeSuccess', function(event, toState) {
                var title = (toState.data && toState.data.title) 
                    ? toState.data.title 
                    : 'Default title';
                $timeout(function() {
                    el.text(title);
                }, 0, false);
            };);
        }
    };
}

angular.module('myApp').directive('dynamicTitle', dynamicTitle);

And attach it to your <title>

<title dynamic-title></title>

You can create an AngularJS factory, inject it, modify it by calling 'Title.setTitle()' from controllers

 <html ng-app="app" ng-controller="Ctrl">
   <head>
     <title>{{ Title.title() }}</title>

  app.factory('Title', function() {
   var title = 'Hello';
   return {
     title: function() { return title; },
     setTitle: function(newTitle) { title = newTitle }
   };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM