2

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?

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
balteo
  • 23,602
  • 63
  • 219
  • 412

1 Answers1

2

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...

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • The point that "controller does not belong to state. It belongs to view!" helped! – Ram Jul 03 '18 at 11:12