Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Page Title with Angular and UI-Router based on data in controller

I'm currently using the directive found in this question to change my page titles.

Set Page title using UI-Router

Then, in my app.js file, I append the pageTitle to data, like so:

.state('home', {
  url: '/home'
  templateUrl: 'home.html'
  controller: 'homeController'
  data: {
    pageTitle: 'Home'
  }
})

But say, for instance, if homeController had a $scope.todaysDate variable that was fetched from a service. Is there a way to access that variable in my router, so I can change data and pageTitle to something like:

data: {
  pageTitle: 'Home ' + $scope.todaysDate
}

I'm able to go into the controller and using $rootScope.pageTitle = 'some value' I can see it changes the variable to 'some value' when I look in the Batarang console tool, but the actual page title doesn't change.

like image 645
twinb Avatar asked Jul 11 '14 18:07

twinb


1 Answers

Maybe a resolve would work in this case. If you want to make sure some data is always available to a state controller you can use a resolve. For example lets say I had a service called, "calendar" and it exposes a function called, "getTodaysDate". I could do the following:

.state('home', {
    url: '/home',
    templateUrl: 'home.html',
    controller: 'homeController',
    resolve:{
            pageTitle:  function(calendar){
            return 'Home ' + calendar.getTodaysDate();
        }
    }
})

Now "pageTitle" will be resolved and injected into "homeController" before the state change. Hope this helps.

like image 143
Nick Avatar answered Sep 30 '22 18:09

Nick