【问题标题】:Binding ng-click to ng-repeat on a dynamic array在动态数组上绑定 ng-click 到 ng-repeat
【发布时间】: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


【解决方案1】:

将您的 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 数组。应该可以正常工作。

【讨论】:

  • 恐怕我听不懂。我很确定我正在通过修改$scope.hand 直接操作hand 数组。感谢您通过索引的技巧 - 这在其他方面很有帮助:)
猜你喜欢
  • 2015-06-21
  • 2016-06-16
  • 2013-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多