我有一个数组hand
。我使用ng-repeat="card in hand"
来迭代这些卡片。我ng-click="select(card)"
用卡片做了一些事情。
使用hand
的初始值时效果很好,但是一旦我开始向hand
数组添加卡片,ng-click
就不会再触发了。
如何在动态阵列的ng-click
中触发ng-repeat
?
card.html:
<div>
<h1>{{data.title}}</h1>
<p>{{data.description}}</p>
<button ng-click="select(data)">Select</button>
</div>
hand.html
<card ng-repeat="card in hand" data="card"></card>
card.js:
app.directive('card', function() {
return {
restrict: 'E',
scope: {
data: '='
},
templateUrl: 'card.html',
controller: 'HandCtrl'
};
});
hand.js:
app.directive('hand', function() {
return {
restrict: 'E',
scope: {
data: '='
},
templateUrl: 'hand.html',
controller: 'HandCtrl'
};
});
handCtrl.js:
app.controller('HandCtrl', ['$scope', 'getHand', function($scope, getHand) {
getHand.then(function(hand) {
$scope.hand = hand;
$scope.select = function(card) {
card.selected = true;
$scope.hand.splice(card.position, 1);
};
});
}]);
代码中的其他地方......
app.controller('DeckCtrl', ['$scope', 'getDeck', 'getHand', function($scope, getDeck, getHand) {
getDeck.then(function(deck) {
$scope.deck = deck;
getHand.then(function(hand) {
$scope.hand = hand;
$scope.drawCard = function() {
var card = deck.splice(0, 1)[0];
// ng-repeat shows this new card, but ng-click doesn't trigger
$scope.hand.push(card);
};
});
});
}]);
由
触发<button ng-click="drawCard">Draw</button>
答案 0 :(得分:2)
将ng-repeat切换为ng-repeat="(index, card) in hand"
并将索引传递给您的函数,如下所示:
<div>
<h1>{{data.title}}</h1>
<p>{{data.description}}</p>
<button ng-click="select(index)">Select</button>
</div>
并更新您的javascript代码以直接操作hand
数组。应该工作正常。