Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 $broadcasting 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.

like image 823
Levi Avatar asked Jun 03 '26 21:06

Levi


1 Answers

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);
             });
    }
}}); 
like image 137
shershen Avatar answered Jun 06 '26 11:06

shershen