AngularJS - 控制器方法没有被调用ng点击 - 没有错误

时间:2012-11-08 19:20:15

标签: javascript angularjs

如果单击按钮,我会尝试调用方法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>
...

3 个答案:

答案 0 :(得分:38)

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

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

答案 1 :(得分: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

答案 2 :(得分:-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”功能,并自然地编码您想要的任何内容,从而间接访问外部控制器。