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>
...
You shouldn't be using curly braces ({{ }}
) in the ng-click expression. You should write:
<button ng-click="removePlayer(player.id)">Remove</button>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With