I am trying to learn AngularJS. For my first project I want to create a small scorekeeping application. I am taking data from a JSON file then I want to update it on the screen depending on who scores.
I can't seem to figure out how to update the specific goal field using Angular. My current application pushes a new row to the scoresheet:
'use strict';
/* Controllers */
function ScoreKeeper($scope, $http) {
$http.get('json/hometeam.json').success(function(data) {
$scope.hometeam = data;
});
$scope.addGoal = function() {
$scope.hometeam.push({goals: +1});
};
}
This is the table I am currently using:
<table class="table table-hover">
<thead>
<th>Player ID</th>
<th>No.</th>
<th>Name</th>
<th>GP</th>
<th>G</th>
<th>A</th>
<th>PIM</th>
<th>Goal</th>
<th>Assist</th>
<th>Assist</th>
</thead>
<tbody>
<tr ng-repeat="player in hometeam" >
<td>{{player.playerid}}</td>
<td>{{player.no}}</td>
<td>{{player.name}}</td>
<td>{{player.gp}}</td>
<td>{{player.goals}}</td>
<td>{{player.assists}}</td>
<td>{{player.pim}}</td>
<td><button class="btn btn-small" name="add-goal" type="button" ng-click="addGoal()"><i class="icon-plus"></i></button></td>
</tr>
</tbody>
</table>
I want to be able to click addGoal for the specific player, and then update their goal total. Right now, the current function is creating a new row with goal being 1 and all the other fields are empty.
I'm quite lost on this one, the data is rendering correctly on refresh, however, my update function is not. I know .push() is not the correct method, however I can't seem to find a good resource for Angular to figure out what would be the right method to use. Any help is greatly appreciated. Thank you.
Instead of creating a new array item with push, you need to increment the goals property of the associated player item. ng-click="addGoal(player)".
$scope.addGoal = function (player) {
player.goals += 1;
};
or just
ng-click="player.goals = player.goals + 1"
I guess you want to add element into player.goals, correct?
Then you can do:
<button ng-click="addGoal($index)">
in js:
$scope.addGoal = function(index) { $scope.hometeam[index].goals++; };