javascript – Angular js foreach只返回数组中的最后一项

前端之家收集整理的这篇文章主要介绍了javascript – Angular js foreach只返回数组中的最后一项前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试从 JSON返回每个项目对象并使用angular.forEach()计算其值,但只返回最后一项.由于我不能进行任何评估.有趣的是,如果我做console.log(),它会逐个显示每个项目.

我怎样才能获得每件商品并对其进行评估?

如果你知道更好的方法,请教我.

JS(angularjs):

  1. angular.module('bLiApp')
  2. .controller('AddDataCtrl',['$scope','DataService',function ($scope,DataService) {
  3.  
  4. DataService.getItems().success(function(data) {
  5.  
  6. $scope.items = data.category.items;
  7.  
  8. angular.forEach($scope.items,function(item) {
  9.  
  10. // This is where I'm having problem with return data...
  11. if (item.amount < 600) {
  12. $scope.amountchecker = 'low';
  13. } else if (item.amount >= 600 && item.amount <= 650) {
  14. $scope.amountchecker = 'average';
  15. } else if (item.amount > 650) {
  16. $scope.amountchecker = 'too high';
  17. }
  18.  
  19. });
  20. });
  21. }]);

HTML(angularjs):

  1. <div class="add-data" ng-controller="AddDataCtrl">
  2. <div class="data-Box clearfix" ng-repeat="item in items">
  3. <article class="item">
  4. <p>{{amountchecker}}</p>
  5. <p><span class="month">{{ item.month.substring(0,3) }}</span></p>
  6. <p class="cost">{{item.cost | currency:"&pound;"}}</p>
  7. </article>
  8. </div>
  9. </div>

非常感谢

解决方法

您实际上不需要forEach循环来实现:
  1. <div class="add-data" ng-controller="AddDataCtrl">
  2.  
  3. <div class="data-Box clearfix" ng-repeat="item in items">
  4. <article class="item">
  5. <p>
  6. <span ng-if="item.amount < 600">Low</span>
  7. <span ng-if="item.amount >= 600 && <= 650">Average</span>
  8. <span ng-if="item.amount < 650">Too high</span>
  9. </p>
  10. <p><span class="month">{{ item.month.substring(0,3) }}</span></p>
  11. <p class="cost">{{item.cost | currency:"&pound;"}}</p>
  12. </article>
  13. </div>
  14. </div>

那应该做的.请注意,这只会显示金额,如果您想在模型中更改它(如果您必须发回刚评估的数据),您应该更改控制器中的数据:

  1. angular.forEach($scope.items,function(item) {
  2. item.amountChecker; // declare a new property for each item in $scope.items
  3. // then we set the value for each item
  4. if (item.amount < 600) {
  5. item.amountChecker = 'low';
  6. } else if (item.amount >= 600 && item.amount <= 650) {
  7. item.amountChecker = 'average';
  8. } else if (item.amount > 650) {
  9. item.amountChecker = 'too high';
  10. }
  11.  
  12. });

这应该在$scope.items对象中添加一个新行,其中amountChecker将分配给每个项目.然后,在ng-repeat中,您还可以显示该值:item.amountChecker.

这次,它将调用每个项目的属性amountChecker,而不是$scope.amountchecker中存储的最后一个值.

请注意,Goodzilla实际上以较短的方式回答评论:)

猜你在找的JavaScript相关文章