【问题标题】:Is it possible to two way bind variables between nested isolate scopes?嵌套隔离范围之间是否可以通过两种方式绑定变量?
【发布时间】:2015-09-01 04:39:12
【问题描述】:

考虑下面的嵌套指令。我一直在尝试在嵌套指令的隔离范围之间绑定变量,并且无法实现双向绑定。

在示例中,我希望 outerPower 绑定到 innerPower 并在 innerPower 数字增加时更改。

检查小提琴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;
        }
    };
});

【问题讨论】:

    标签: javascript angularjs isolate-scope


    【解决方案1】:

    对于双向绑定,您需要使用= 作为范围变量。 &amp; 仅应在您的指令需要在父范围内执行函数时使用。

    JSFiddle

    scope: {
       innerPower: '='
    },
    

    【讨论】:

    • 两个答案相同怎么办?我的是 21 秒后,但我在写我的时候没有看到你的答案,所以我应该删除还是保持原样?
    • 不确定:p 我认为离开它可能没问题。
    【解决方案2】:

    只换一行

    scope: {
         innerPower: '=' //instead of &
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-26
      • 2016-04-28
      • 2015-06-15
      • 2011-01-06
      相关资源
      最近更新 更多