简体   繁体   中英

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 ? (link function cause I have access to the element parameter directly ? or in the controller ?

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

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