javascriptangularjsangularjs-directivecontrolleras

AngularJS 1.4: How to create two-way binding using bindToController and controllerAs syntax


Okay, this is really bugging me. I have a directive with isolate scope, using the controllerAs syntax and bindToController:

function exampleDirectiveFactory() {
    var bindings = {
        foo: '=',
        bar: '@'
    }

    return {
        bindToController: true,
        controller      : 'ExampleController',
        controllerAs    : 'vm',
        scope           : bindings,
        template        : 'foo = {{ vm.foo }}<br />bar = {{ vm.bar }}'
    };
}

Assuming a usage like this:

<example foo="FOO" bar="BAR"></example>

...I expect the value of vm.foo to be two-way bound to the value of the foo attribute. Instead, it is undefined.

The value of vm.bar is equal to the attribute value bar of the HTML element, which I expect.

When I try to change the value of vm.bar using a filter, no change persists.

When I store the filtered value of vm.bar to a new variable, vm.baz, that works as expected.

Here is a fiddle

So my question has two parts:

A) Why is the value of vm.foo undefined when using '='?

B) Why can't I change the value of vm.bar in the scope of the controller, even if that change does not propagate to the HTML element attribute (which it shouldn't, because I'm using '@')?


Solution

  • 1.4 changed how bindToController works. Though it appears that angular's documentation is still referring to the field as true/false. Now it can accept an object just like the scope attribute where the attributes indicate what you want bound and how to bind it.

    function exampleDirectiveFactory() {
        var bindings = {
            foo: '=',
            bar: '@'
        }
    
        return {
            bindToController: bindings, //<-- things that will be bound
            controller      : 'ExampleController',
            controllerAs    : 'vm',
            scope           : {}, //<-- isolated scope
            template        : 'foo = {{ vm.foo }}<br />bar = {{ vm.bar }}'
        };
    }
    

    In addition, in your fiddle, FOO is undefined on the parent scope, so when it binds, it will pull that undefined into the directive's bound controller's scope.

    Further reading: One major thing that this new bindToController syntax allows is the ability for the directive to not be an isolated scope and still identify what to bind. You can actually set scope to true on your directive to have a new child scope that will inherit from it's ancestors.