我遇到过使用ng-repeat来显示指令的情况,该指令负责计算子总数并使用双向绑定将该子总数添加到我的总数中。
但是,通过使用ng-repeat,它会添加到ng-repeat的范围而不是我的控制器。我怎样才能让它正常工作?
编辑:我找到了一个解决方案,但不确定它是不是最好的方法......
我改变了:
<div ng-repeat='item in myArray'>
<add-it-up sub-total='total1'></add-it-up>
</div>
到
<div ng-repeat='item in myArray'>
<add-it-up sub-total='$parent.total1'></add-it-up>
</div>
它正在工作。有更好的方法吗?
Plunker:http://plnkr.co/edit/lqh0z93yc5Q5E2gNBdtG?p=preview
<!DOCTYPE html>
<html ng-app='testApp'>
<head>
<script data-require="angular.js@1.3.15" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
</head>
<body ng-controller='TestCtrl'>
<!-- This doesn't work -->
<div ng-repeat='item in myArray'>
<add-it-up sub-total='total1'></add-it-up>
</div>
{{total1}}
<br />
<!-- This does work -->
<add-it-up sub-total='total2'></add-it-up>
<add-it-up sub-total='total2'></add-it-up>
<add-it-up sub-total='total2'></add-it-up>
{{total2}}
<script>
var app = angular.module('testApp', []);
app.controller('TestCtrl', ['$scope', function($scope) {
$scope.myArray = [0, 1, 2];
$scope.total1 = 0;
$scope.total2 = 0;
}])
app.directive("addItUp", function () {
return {
restrict: 'E',
scope: {
subTotal: "="
},
controller: ['$scope', '$timeout', function ($scope, $timeout) {
$timeout(function() {
console.log($scope.subTotal)
$scope.subTotal += 5;
console.log($scope.subTotal)
})
}]
}
})
</script>
</body>
</html>
答案 0 :(得分:1)
您必须向包含$scope
的{{1}}添加一个对象。否则,此属性会被total1
:
ng-repeat sub-scopes
看看this updated plnkr。有关更多信息,请访问Understanding Scopes。