Ad

Binding Ng-click To Ng-repeat On A Dynamic Array

Context

I have an array hand. I'm using ng-repeat="card in hand" to iterate through the cards. I have ng-click="select(card)" to do something with said card.

This works fine when using the initial values of hand, but once I start adding cards to the hand array, ng-click no longer fires.

Question

How can I get ng-click to fire in an ng-repeat on a dynamic array?

Code (simplified)

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);
        };
    });
}]);

elsewhere in the code...

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);
            };
        });
    });
}]);

which is triggered by

<button ng-click="drawCard">Draw</button>
Ad

Answer

switch your ng-repeat to ng-repeat="(index, card) in hand" and pass the index to your function like this:

<div>
    <h1>{{data.title}}</h1>
    <p>{{data.description}}</p>
    <button ng-click="select(index)">Select</button>
</div>

and update your javascript code to manipulate the hand array directly. Should work fine.

Ad
source: stackoverflow.com
Ad