Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"controller as" vs isolate scope

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.

like image 746
thorn0 Avatar asked May 06 '14 13:05

thorn0


People also ask

What is isolate scope?

Isolated scope directive is a scope that does not inherit from the parent and exist on its own. Scenario: Lets create a very simple directive which will show the object from the parent controller.

What is the difference between the scope of a directive and the scope of a controller?

No difference. It is same object.

What is true about scope in AngularJS?

AngularJS ScopeThe scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller.


1 Answers

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

like image 80
thorn0 Avatar answered Sep 21 '22 04:09

thorn0