【发布时间】:2016-04-01 20:51:40
【问题描述】:
上下文
我有一个数组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>
【问题讨论】:
-
添加新卡的代码在哪里。向我们展示完整的代码。
-
@Shyju 添加了代码。
-
在将其推送到数组之前,您确定
card中有一个有效的对象吗? -
Yes--
ng-repeat显示新卡片(标题、描述等)。只是单击“选择”按钮不会仅在新卡上触发ng-click。 -
你的问题是你做了
$scope.hand.splice(card.position, 1);但是你从来没有更新其他卡片card.position ;)
标签: javascript angularjs angularjs-ng-repeat angularjs-ng-click