6

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.

Community
  • 1
  • 1
twinb
  • 166
  • 1
  • 2
  • 9

1 Answers1

2

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.

DineshKP
  • 364
  • 2
  • 12
Nick
  • 19,198
  • 51
  • 185
  • 312
  • Thanks for mentioning resolve. It seems to be the correct approach. I haven't got it working yet. I think I'm doing something wrong with the code in my factory. (I said it was a service earlier but it's actually a factory) – twinb Jul 15 '14 at 21:01
  • @twinb what you have IS a service. There is more than one way to register a service on a module. You are using the factory method (most common) Take a look here for details: https://docs.angularjs.org/guide/services – Nick Jul 17 '14 at 20:17
  • @twinb are you having any luck with this? I would be glad to provide you a working example if it would help. This is a pretty common use case and I think you might just be struggling with a small learning curve. – Nick Jul 20 '14 at 18:14
  • sorry for the late response. I couldn't get it working so kinda gave up on it for now. I understand how resolve works but I think I'm goofing things up in the service/factory(good point btw) with the function I was trying to call. A working example would be great if it didn't take too much of your time. – twinb Jul 21 '14 at 17:16