20

removePlayer(playerId)如果单击按钮,我会尝试调用该方法。但是,该方法没有被调用,或者至少它里面的语句没有被触发,因为我console.log()在顶部放了一个语句。

控制台是空的,所以我真的一无所知。这是我的代码:

控制器:

function appController($scope) {
    $scope.players = [];
    var playercount = 0;

    $scope.addPlayer = function(playername) {

        $scope.players.push({name: playername, score: 0, id: playercount});
        playercount++;
    }

    function getIndexOfPlayerWithId(playerId) {
        for (var i = $scope.players.length - 1; i > -1; i--) {
            if ($scope.players[i].id == playerId)
                return i;
        }
    }

    $scope.removePlayer = function(playerId) {
        console.log("remove");
        var index = getIndexOfPlayerWithId(playerId);
        $scope.players.slice(index, 1);
    }
}
appController.$inject = ['$scope'];

HTML:

...
<table id="players">
        <tr ng-repeat="player in players">
            <td>{{player.name}}</td>
            <td>{{player.score}}</td>
            <td><button ng-click="removePlayer({{player.id}})">Remove</button></td>
        </tr>
    </table>
...
4

3 回答 3

38

{{ }}您不应该在 ng-click 表达式中使用花括号 ( )。你应该写:

<button ng-click="removePlayer(player.id)">Remove</button>

于 2012-11-08T19:39:11.653 回答
4

ng-repeat创建一个新的范围,所以它不知道是什么removePlayer。你应该能够做这样的事情:

<table id="players">
    <tr ng-repeat="player in players">
        <td>{{player.name}}</td>
        <td>{{player.score}}</td>
        <td><button ng-click="$parent.removePlayer({{player.id}})">Remove</button></td>
    </tr>
</table>

请参阅https://groups.google.com/forum/?fromgroups=#!topic/angular/NXyZHRTAnLA

于 2012-11-08T19:31:34.410 回答
-1

如前所述,ng-repeat 创建它自己的范围,外部控制器范围不可用。但是由于在 JS 中您使用的是真正的对象,因此请编写如下内容:

<tr ng-repeat="player in players">
    <td>{{player.name}}</td>
    <td>{{player.score}}</td>
    <td><button ng-click="player.removePlayer()">Remove</button></td>
</tr>

事先,在控制器初始化的某个地方,您可以将“removePlayer”函数分配给每个播放器对象,并自然地编写任何您想要的代码,从而间接访问外部控制器。

于 2013-08-28T18:06:06.457 回答