简体   繁体   中英

AngularJS - Dynamic Title with interpolation

Problem

I am currently trying to figure out a way to dynamically change the <title></title> template when a $route changes. I've seen various solutions for doing this which involve either $broadcast ing a message or passing around a factory to setTitle or something to that effect. I would like if I could simply define this at my $routeProvider level but also allow it to be flexible enough to use a variable on the current scope of the $route .

What I Have

Currently I have a somewhat working solution that uses $interpolate to achieve what I want; the problem is that if, for instance, the property is set after an AJAX call, the template isn't updated.

routes.coffee

angular.module('app').config ['$routeProvider', ($routeProvider) ->
  $routeProvider
    .when '/',
      templateUrl: 'templates/home.html'
      controller: 'Home'
    .when '/person/:id'
      templateUrl: 'templates/person.html'
      controller: 'Person'
      title: '{{name}} ({{age}})'
]

lwTitle.coffee

angular.module('app').directive 'lwTitle', ['$route', '$interpolate', ($route, $interpolate) ->
  link: (scope, el) ->
    whenRouteScopeChanges = -> $route.current?.scope
    updateTitle = (routeScope) ->
      if routeScope
        title = $route.current?.$$route.title or 'Home'
        el.html $interpolate("#{title} - My App")(routeScope)

    scope.$watch whenRouteScopeChanges, updateTitle
]

Again, this works; but if, for instance, the person and age attributes on routeScope (in the case of the /person/:id route) are set only after an AJAX call, I get an empty string for their values.

Is there a way to achieve what I'm looking for? I really want to set the <title></title> element's template dynamically, as well as to tell it the scope of it is routeScope when the route changes.

Thanks in advance.

You should use resolve property on your route - then first your ajax call will retrieve data and then route will be populated.

route.resolve - An optional map of dependencies which should be injected into the controller.

it can look like this

 //normal javascript
  $routeProvider.when('/', {
  templateUrl: 'templates/home.html'
  resolve:{
    promiseObject:  function($http){
            return $http({method: 'GET', url: '/someUrl'})
            .then (function (data) {
              return doSomeStuffFirst(data);
             });
    }
}}); 

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