Search code examples
javascriptangularjsisolate-scope

Is it possible to two way bind variables between nested isolate scopes?


Consider the nested directives below. I have been trying to bind variables between the isolate scopes of nested directives and have been unable to achieve a two way binding.

In the example I want the outerPower to bind to the innerPower and change when the innerPower number increments.

Check the fiddle http://jsfiddle.net/hally9k/sqea6Ln7/

testApp.directive('innerDirective', function () {
    return {
        scope: {
           innerPower: '&'
        },
        template: '<div><p>Inner Power = {{innerPower}}</p>' +
            '<button ng-click="increment();">Power up!</button>' +
            '</div>',
        controller: function ($scope, $element, $attrs) {
           $scope.increment = function() {
                ++$scope.innerPower;
           }
        }
    };
});

testApp.directive('outerDirective', function () {
    return {
        scope: {

        },
        template: '<div><p>Outer Power = {{outerPower}}</p>' +
            '<div inner-directive inner-power="outerPower"></div>' +
        '</div>',
        controller: function ($scope, $element, $attrs) {
           $scope.outerPower = 0;
        }
    };
});

Solution

  • For bi-directional binding, you need to use = for the scope variable. & should only be used when your directive needs to execute a function in the parent scope.

    JSFiddle

    scope: {
       innerPower: '='
    },