gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 04:42:22 26 4
gpt4 key购买 nike

我尝试使用 angular.forEach() 从 JSON 返回每个项目对象并评估其值,但只返回最后一个项目。因此,我无法进行任何评估。有趣的是,如果我执行 console.log(),它会逐一显示每一项。

如何获取每个项目并对其进行评估?

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

JS( Angular ):

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( Angular ):

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

这应该可以完成工作。请注意,这只会显示金额,如果您想在模型中更改它(如果您必须发回刚刚评估的数据),您应该更改 Controller 中的数据:

  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 实际上在评论中以较短的方式回答了 :)

关于javascript - Angular js foreach只返回数组中的最后一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25886495/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com