2013-02-05 47 views
0

我正在学习AngularJS。对于我的第一个项目,我想创建一个小型记分应用程序。我正在从JSON文件中获取数据,然后我想根据谁的分数在屏幕上更新它。如何使用按钮将使用AngularJS的字段添加到字段中?

我似乎无法弄清楚如何使用Angular更新特定的目标字段。我现在的应用程序将一个新行记录表:

'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}); 
    }; 
} 

这是我目前使用的表格:

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

我希望能够点击addGoal为特定的球员,然后更新他们的总目标。目前,当前函数创建一个目标为1的新行,其他所有字段都为空。

我很迷茫,这个数据刷新正确,但是,我的更新功能不是。我知道.push()不是正确的方法,但我似乎无法找到Angular的一个很好的资源来找出什么是正确的方法来使用。任何帮助是极大的赞赏。谢谢。

回答

1

您不需要通过push创建新的数组项目,而需要增加关联播放器项目的goals属性。 ng-click="addGoal(player)"

$scope.addGoal = function (player) { 
    player.goals += 1; 
}; 

或只是

ng-click="player.goals = player.goals + 1"

+0

运行完美,非常感谢你。这现在看起来很有意义。 – Neil

1

我猜你要添加的元素插入player.goals,是否正确?

然后,你可以这样做:

<button ng-click="addGoal($index)"> 

在JS:

$scope.addGoal = function(index) { $scope.hometeam[index].goals++; }; 
相关问题