Are there different ways of declaring the controll

2020-04-16 06:03发布

问题:

I have an interrogation about the Angular UI router.

Is it any different to declare the controller associated with the state at the top level or at the view level?

See snippet below:

.state('signup', {
    controller: 'SignupCtrl',//HERE
    views: {
        '@': {
            controller: 'SignupCtrl',//OR THERE
            templateUrl: 'signup/views/signup.html'
        }
    }
})

Is it any different to declare the controller //HERE //OR THERE?

If so what is the difference?

回答1:

There is a big difference - because only one or the other is used. In fact, the most important message is:

controller does not belong to state. It belongs to view!

In case if there is a views : {} object, each view can have its own controller defined.

.state('myState', {
    views: {
        '@': {
            controller: 'SignupCtrl',
            templateUrl: 'signup/views/signup.html'
        },
        'hint@': {
            controller: 'HintCtrl',
            templateUrl: 'signup/views/signup.html'
        }
    }
})

There is one exceptional views definition. It happens, if we target the ui-view="" in the state parent. In that case, we can still writ it like this:

.state('myState', {
    views: {
        '': {
            controller: 'SignupCtrl',
            templateUrl: 'signup/views/signup.html'
        },
    }
})

But we can use simplified version, equal to this definition:

.state('myState', {
    controller: 'SignupCtrl',
    templateUrl: 'signup/views/signup.html'
})

So last two are equal at the end. But again, in the last example we just used simplifed version. Controller always belong to view (template) not to state...