2

Currently getting to know ui-router. I have this:

$stateProvider
.state('taxonomy', {
    url: '/lista/:taxonomy',
    views: {
        '' : {
            templateUrl: '/js/app/taxonomy/index.tpl.html',
            controller: 'taxonomy.index.controller',
            controllerAs: 'vm',
            myClass: 'classForThisOne'
        },
        'sidebarRight@': {
            templateUrl: '/js/app/taxonomy/sidebarRight.tpl.html',
            /* no controller = no variable */
        }
    }
})

.state('taxonomy.detail', {
    url: '/:mode/:taxonomyId?',
    views: {
        'sidebarRight@' : {
            templateUrl: '/js/app/taxonomy/detail.tpl.html',
            controller: 'taxonomy.detail.controller',
            controllerAs: 'vm',
            myClass: 'myClassForThisController'
        },

        '': {
            myClass: 'myClassForController taxonomy.index.controller'
        }
    }
});

What I would like to be able to do is to be able of the 'myClass' property inside the controller I specified with the controller and controllerAs variable. Can this be done somehow?

I tried to watch the $stateChangeStart event and $stateProvider.decorator('views', function (state, parent) { }) but without any luck.

2

2 Answers 2

1

You can pass through custom data like this:

views: {
    '' : {
        templateUrl: '/js/app/taxonomy/index.tpl.html',
        controller: 'taxonomy.index.controller',
        controllerAs: 'vm',
        // the 'data' property can be used for custom data
        data: {
            myClass: 'classForThisOne'
        }
    },

Then in your controller, inject $state, and retrieve the data:

function myCtrl($state){
    var myClass = $state.current.data.myClass;
}

See for reference: https://github.com/angular-ui/ui-router/wiki#attach-custom-data-to-state-objects

Note that above is best practice (use the 'data' object), but you should also be able to do it like you do:

views: {
    '' : {
        templateUrl: '/js/app/taxonomy/index.tpl.html',
        controller: 'taxonomy.index.controller',
        controllerAs: 'vm',
        myClass: 'classForThisOne'
    },

and retrieval:

var myClass = $state.current.myClass;
Sign up to request clarification or add additional context in comments.

1 Comment

Nah - $state.current.data and $state.current.myClass give me empty (as in 'undefined') values.
0

I've not tried this, but this should work. Write following in your controller:

$scope.getClass = function() {
    var currentState = $state.current;
    // Or use any other named view instead of "sidebarRight@"
    return currentState.views['sidebarRight@'].myClass;
};

1 Comment

But I don't know the view's name in the controller, do I. So I would need to hardcode 'sidebarRight@', which I do not want.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.