Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - controller method doesn't get called on ngClick - no error

I try to call the method removePlayer(playerId) if a button gets clicked. But, the method doesn't get called, or at least the statements inside it aren't firing, because I put a console.log() statement at the top.

The console is empty, so I'm really clueless. Here is my code:

Controller:

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>
...
like image 405
11684 Avatar asked Nov 08 '12 19:11

11684


Video Answer


2 Answers

You shouldn't be using curly braces ({{ }}) in the ng-click expression. You should write:

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

like image 101
pkozlowski.opensource Avatar answered Oct 04 '22 17:10

pkozlowski.opensource


ng-repeat creates a new scope, so it doesn't know what removePlayer is. You should be able to do something like this:

<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>

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

like image 38
dnc253 Avatar answered Oct 04 '22 15:10

dnc253