简体   繁体   中英

Why can you define a controller on your routes in AngularJS?

Leaving directives aside, we can and do assign controllers generally somewhere in the middle of a view, just to modify a particular piece HTML with some state or behavior. You can do this on any level, even the top most level. The view and controller are tightly coupled together.

What is the reason you can assign a controller on route level as well? I never understood this, what is the philosophy behind this? What is the added benefit of assigning a controller outside of the view rather than in the top of the view itself. Surely not the ability to switch a controller for another implementation; I've never seen this done.

/edit: perhaps it is necessary in order to do a manual resolve that gets injected? (See John Papa's example )

I'm sure there are other valid reasons for having the option to define a controller to a route, but I think this is a pretty big one. Think of this scenario:

  • you have a template you'd like to reuse with various routes/states
  • you may want to assign a different controller to the template based on the route.

If you use ng-controller in your template, you can't (to my knowledge) reuse that template with a different controller.

With assigning the controller via the route, you have more flexibility.

standard approach

I'm going to use the UI.Router in this example as that's all I have experience with.

.state( 'users', {
    templateUrl: 'person.html'
    controller: 'UsersController'
})

.state( 'admin', {
    templateUrl: 'person.html'
    controller: 'AdminController'
})

Same template, different routes, with different controllers.

dynamic approach

Surely not the ability to switch a controller for another implementation

I won't argue the merits/demerits of this use-case but I've used it myself once or twice and I've seen it discussed here on SO and other blogs.

.state( 'entity', {
    templateUrl: 'person.html'
    controller: function( ...injectables ){
        var UserController = function(){ ... }
        var AdminController = function(){ ... }

        var ControllerClass = isAdmin ? AdminController : UserController;
        return new ControllerClass()           
    }
})

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