简体   繁体   English

带有控制器的路由:在路由或模板定义中?

[英]Routes with controllers: In route or template definition?

When defining a route with a template, there's basically two ways how you can set the controller corresponding to the view: 使用模板定义路线时,基本上有两种方法可以设置与视图相对应的控制器:

  • In the route: 在路线中:

     $routeProvider .when('/phone/:phoneId', { controller: 'PhoneDetailController', templateUrl: 'phone.detail.html', } }); 
  • In the template: 在模板中:

     $routeProvider .when('/phone/:phoneId', { templateUrl: 'phone.detail.html', } }); 
     <div ng-controller="PhoneDetailController"> <!-- [...] --> </div> 

What are the differences, what is recommended, and why? 有什么区别,建议什么,为什么?

If you look at the ui-router source code, inside viewDirective.js you can see how the controller is instantiated: 如果查看ui-router源代码,请在viewDirective.js内看到如何实例化控制器:

if (locals.$$controller) {
    locals.$scope = scope;
    locals.$element = $element;
    var controller = $controller(locals.$$controller, locals);
    if (locals.$$controllerAs) {
        scope[locals.$$controllerAs] = controller;
    }
    $element.data('$ngControllerController', controller);
    $element.children().data('$ngControllerController', controller);
}

So basically your two options are going to do essentially the same thing. 因此,基本上,您的两个选项将做基本上相同的事情。 So it is up to you, and what you believe the best semantics to be. 因此,这取决于您,以及您认为最佳的语义是什么。 Personally I prefer to put my controller names inside the state def, as I like to keep my templates as view oriented (and reusable) as possible. 就我个人而言,我更喜欢将控制器名称放在状态def中,因为我希望模板始终保持面向视图(并且可重用)。 Also it seems to be the most common way to do things, so others will be able to understand your code more easily. 同样,这似乎是最常见的处理方式,因此其他人将能够更轻松地理解您的代码。

Personally I use the first version because of the better and central configuration. 我个人使用第一个版本是因为更好和集中的配置。 I think there is not a big difference but like in Comment from Filype I did not see Version 2 that often. 我认为并没有太大的区别,但是就像Filype的Comment中一样,我并不经常看到版本2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM