在动态数组上绑定ng-click到ng-repeat

时间:2015-12-28 00:02:13

标签: javascript angularjs angularjs-ng-repeat angularjs-ng-click

上下文

我有一个数组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>

1 个答案:

答案 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数组。应该工作正常。