Question

I'd like to use the 'controllerAs' option in my directives. Let me cite the reasoning from "An AngularJS Style Guide for Closure Users at Google":

Why? Putting methods and properties directly onto the controller, instead of building up a scope object, fits better with the Google Closure class style. Additionally, using 'controller as' makes it obvious which controller you are accessing when multiple controllers apply to an element. Since there is always a '.' in the bindings, you don't have to worry about prototypal inheritance masking primitives.

But I can see an issue with using this approach if the directive has isolate scope bindings.

angular.module('cmw').directive('fooWidget', function() {
    return {
        controller: function() {
            this.qux = '123';
        },
        controllerAs: 'fooWidget',
        scope: {
            bar: '='
        },
        template: ' {{fooWidget.qux}}  {{bar}} '
    };
});

In this case, the bar property is attached to the scope, not to the controller, which results in a confusing inconsistent situation where different properties should be looked for in different places. What is the 'official' recommended way to work around this?

UPDATE: see the GitHub issue about this.

Was it helpful?

Solution

This was resolved in Angular 1.3 by adding the bindToController property to the directive API.

OTHER TIPS

It's hard to find an "official" pattern for doing this. Personally, I think it depends on what your goal is.

If you want to expose information from a Directive to the outside world, use the Isolated Scope as that's one of the reasons it is there. That 'API' doesn't have to be completely defined in the Directive either, it can be defined in an AngularJS Service which you inject into a Directive and expose through the Isolated Scope that way you have a Directive that is concerned mainly with the UI along with a service that handles any business logic.

If you are communicating between Directives, that's where a Controller is preferred.

But to try and get some more official information, here is information from the AngularJS website on the use of Controllers with Directives:

Best Practice: use controller when you want to expose an API to other directives. Otherwise use link.

I've personally never seen Controllers being used in Directives except for Directive-to-Directive communication. I'm not saying you can't use them, I've just not seen it. Also, if you wanted to expose the Controller logic to the outside world, then you would have to bind to the isolated scope anyways so it all really depends on what you want to do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top