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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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 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: docs.angularjs.org/guide/services
@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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.