ng-repeat中的孤立范围指令未按预期工作

时间:2016-08-25 14:03:15

标签: angularjs angularjs-directive angularjs-ng-repeat

我有一个孤立的范围指令和ng-repeat中的清除按钮循环。

HTML

Controller (parent scope):
<br /> kids: {{kids}}
<br /> lonelyKid: {{lonelyKid}}
<br />
<hr /> Directive (ng-repeat):
<br />
<div ng-repeat="k in kids">
    <button ng-click="communicator.clear()">Clear Data</button>
    <kid k="k" communicator="communicator"></kid>
</div>
<hr /> Directive (not ng-repeat):
<br />
<button ng-click="communicator.clear()">Clear Data</button>
<kid k="lonelyKid" communicator="communicator"></kid>

JS

var app = angular.module('myApp', []);
app.directive("kid", function() {
    return {
        restrict: 'E',
        template: '<input type="text" ng-model="k.name"><br>{{k.name}}<br>',
        scope: {
            k: "=",
            communicator: "="
        },
        controller: function($scope) {
            $scope.k = angular.copy($scope.k);
            $scope.communicator.clear = function() {
                console.log($scope.k)
                $scope.k.name = ''
                console.log($scope.k)
            }
        }
    };
});
app.controller('myController', function($scope) {
    $scope.kids = [{
        name: "Ang",
        age: 15
    }, {
        name: "Ying",
        age: 14
    }, {
        name: "Ellie",
        age: 2
    }, {
        name: "Smith",
        age: 10
    }];
    $scope.lonelyKid = {
        name: "Ming",
        age: 9
    };
    $scope.communicator = {};
});

当我点击清除按钮时,相应的指令内容应该清楚。但是在我的代码中,如果我点击第一个元素的清除按钮,那么它将清除ng-repeat中的最后一个元素数据而不是第一个元素。如果我们点击循环中不存在的第二个,第三个或清除按钮,它会相同,它会清除循环的最后一个元素。

请告诉我,为什么会这样?我该如何解决这个问题?

Working example

2 个答案:

答案 0 :(得分:0)

请尝试改为:

controller: function($scope) {
  $scope.communicator.clear = function(kid) {
    kid.name = '';
  }
}

在你的模板中:

<div ng-repeat="k in kids">
    <button ng-click="communicator.clear( k )">Clear Data</button>
    <kid k="k" communicator="communicator"></kid>
</div>
<hr /> Directive (not ng-repeat):
<br />
<button ng-click="communicator.clear( lonelyKid )">Clear Data</button>
<kid k="lonelyKid" communicator="communicator"></kid>

plunker

答案 1 :(得分:0)

这种情况正在发生,因为您只有一个communicator,并且每次声明指令时都会覆盖其clear函数。因此,被调用的clear函数是您设置的最后一个函数,在您的情况下,是列表的最后一个元素。

通过在指令的communicator: "="属性中使用scope,这意味着您的控制器和指令之间存在communicator的双向绑定。换句话说,在控制器或指令中使用$scope.communicator引用同一个对象。

解决这个问题的方法可能是每个孩子都有一个沟通者(虽然它可能不是设计方面的最佳解决方案,因为我并不真正理解这个沟通者对象的目的)。

有关工作示例,请参阅this Plunker