简体   繁体   English

Angular指令-什么时候更喜欢在指令内使用控制器?

[英]Angular directive - when to prefer using a controller inside a directive?

I've been seing a lot of directive containing a controller in it. 我一直在寻找很多包含控制器的指令。 What are the pro / cons /differences and use cases compared to put the same code in the link function of the directive ? 将相同的代码放入指令的链接函数中,有哪些优点/缺点/用例?

One directive can use another directive's controller => Ok but what else ? 一个指令可以使用另一个指令的控制器=>好,但是还有什么呢? Is it just to have a more cleaner/separate code ? 仅仅是拥有更简洁/独立的代码吗?

And then, for example, in the case of adding a click event on the directive.. where to put it ? 然后,例如,在指令上添加click事件的情况下。 (link function cause I have access to the element parameter directly ? or in the controller ? (链接功能,因为我可以直接访问element参数?还是可以在控制器中访问?

Thanks for the clarification 感谢您的澄清

In my opinion, one of the main reasons to use a controller to add behavior to a directive (instead of the linking function) is, that you cannot really unit test the logic in a directive's link function (whereas controllers can easily be tested and mocked). 我认为,使用控制器向指令(而不是链接功能)添加行为的主要原因之一是,您无法真正对指令的链接功能中的逻辑进行单元测试(而可以轻松地测试和模拟控制器) )。

Since the controller is injected into the directive's linking function you can easily call (or init) some methods in the controller with the actual element to bind behavior to it. 由于控制器已注入指令的链接函数中,因此您可以轻松地调用(或初始化)控制器中带有实际元素的某些方法来将行为绑定到该方法。

For example: 例如:

angular.module('foo', [])
.controller('MyController', function () {
    this.init = function (element) {
        element.on('click', function () {
            //do something
        });
    };
})
.directive('MyDirective', function () {
    return {
        controller: 'MyController',
        link: function (scope, elem, attrs, ctrl) {
            ctrl.init(elem);
        } 
    };
});

If you're just adding some scope variables that should be displayed in the directive's template (ie nothing that's really crucial to be tested) - a linking function is just fine. 如果您只是添加一些应该在指令模板中显示的范围变量(即,没有什么对测试至关重要),那么链接功能就可以了。

The guys at angular-ui-bootstrap are doing good example of doing it that way: https://github.com/angular-ui/bootstrap/tree/master/src angular-ui-bootstrap的家伙正在以这种方式很好地说明了这一点: https : //github.com/angular-ui/bootstrap/tree/master/src

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

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