Thanks to visit codestin.com
Credit goes to github.com

Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

controllerAs in directives doesn't play well with isolate scope #7635

Closed
@thorn0

Description

@thorn0

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.

As for now I see two alternatives, both not appealing to me:

  1. to create bindings manually by calling $observe for each attribute needed, or
  2. to forgo using 'controllerAs' at all.

It might make sense to introduce another special character for the scope entries in directive definition objects. This character would mean that the given property is a property of the controller, not the scope. What about dot?

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions