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

我正在尝试从 JSON返回每个项目对象并使用angular.forEach()计算其值,但只返回最后一项.由于我不能进行任何评估.有趣的是,如果我做console.log(),它会逐个显示每个项目.

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

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

JS(angularjs):

angular.module('bLiApp')
  .controller('AddDataCtrl',['$scope','DataService',function ($scope,DataService) {

    DataService.getItems().success(function(data) {

      $scope.items = data.category.items;

      angular.forEach($scope.items,function(item) {

        // This is where I'm having problem with return data...
        if (item.amount < 600) {
          $scope.amountchecker = 'low';
        } else if (item.amount >= 600 && item.amount <= 650) {
          $scope.amountchecker = 'average';
        } else if (item.amount > 650) {
          $scope.amountchecker = 'too high';
        }

      });
    });
  }]);

HTML(angularjs):

<div class="add-data" ng-controller="AddDataCtrl">
  <div class="data-box clearfix" ng-repeat="item in items">
    <article class="item">
      <p>{{amountchecker}}</p>
      <p><span class="month">{{ item.month.substring(0,3) }}</span></p>
      <p class="cost">{{item.cost | currency:"&pound;"}}</p>
    </article>
  </div>
</div>

非常感谢

解决方法

您实际上不需要forEach循环来实现:
<div class="add-data" ng-controller="AddDataCtrl">

 <div class="data-box clearfix" ng-repeat="item in items">
    <article class="item">
      <p>
         <span ng-if="item.amount < 600">Low</span>
         <span ng-if="item.amount >= 600 && <= 650">Average</span>
         <span ng-if="item.amount < 650">Too high</span>
      </p>
      <p><span class="month">{{ item.month.substring(0,3) }}</span></p>
      <p class="cost">{{item.cost | currency:"&pound;"}}</p>
    </article>
  </div>
</div>

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

angular.forEach($scope.items,function(item) {
    item.amountChecker; // declare a new property for each item in $scope.items
    // then we set the value for each item
    if (item.amount < 600) {
      item.amountChecker = 'low';
    } else if (item.amount >= 600 && item.amount <= 650) {
      item.amountChecker = 'average';
    } else if (item.amount > 650) {
      item.amountChecker = 'too high';
    }

  });

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

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

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

相关文章

kindeditor4.x代码高亮功能默认使用的是prettify插件,prett...
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小