【发布时间】:2014-11-11 05:58:52
【问题描述】:
我正在尝试使用angular.forEach() 从 JSON 返回每个项目对象并评估其值,但只返回最后一个项目。因此,我无法进行任何评估。有趣的是,如果我使用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:"£"}}</p>
</article>
</div>
</div>
非常感谢
【问题讨论】:
-
你可以尝试在 ng repeat 中添加“track by $index”吗?
-
你不是想说
item.amountchecker = ''吗?因为你每次都在那里覆盖它。 (以及 html 中的{{item.amountchecker}}) -
@Goodzilla,不,我正在测试一些东西。可以忽略。那么你知道发生了什么以及我该如何解决这个问题吗?
-
@ThomasP1988,对不起,我刚刚开始学习 Angular。 $index 是什么意思?
-
@Shaoz 如果您有重复的项目,请参阅documentation。你能告诉我们有问题的数组吗?
标签: javascript angularjs foreach angularjs-scope