简体   繁体   中英

Angularjs ui-router state data on initial load

My routes are like so:

...
.state('some.route', {
    url: '/some/route',
    template: 'someTemplate.html',
    controller: 'SomeCtrl'
    data: {
        title: 'Some Title'
    }
})
...

Every route has a data.title property.

I also have a directive like so

...
app.directive('titleBar', function($state, $rootScope){
    return {
        restrict: 'AE',
        replace: true,
        link: function(scope, element, attrs){
            scope.title = $state.current.data.title; // On initial load, find data.title and bind it
            $rootScope.$on('$stateChangeStart', function(e, toState){
                scope.title = toState.data.title; // On state change, bind new data.title
            }
        },
        template: '<div class="title-bar"> {{ title }} </div>'
    };
});

When you navigate states, the directive works fine and binds the appropriate title.

But when I do a full refresh, it doesn't return the right data for the state I refreshed in. Instead it returns some sort of abstract base state like so:

console.log($state.current);
>>>> OUTPUT
{
    abstract: true,
    name: "",
    url: "^",
    views: null
}   

Any ideas?

So I figured out why this is happening, and am still trying to find a solution.

The directive is in the main layout, before the ui-view. So when you reload the page, the state will obviously be the root state, which then gets updated when the view loads.

SOLUTION UPDATE:

Instead of using $on('$stateChangeStart') I'm now using $on('$viewContentLoaded') .

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