我正在迈出第一步,使用 AngularJS 调用一个 API,该 API 将发送回一个包含我需要的数据的 JSON 对象。我调用 API 并获取响应并将其打印在 HTML 上,根据需要进行迭代。
但我还没有在实际的 Javascript 文件上找到一种方法,可以迭代对项目进行分组和求和,或者将 JSON 的实际值打印到控制台。
app.js
angular.module('dashboard', ['ngResource']);
function DashboardCtrl($scope, $resource) {
$scope.dailyReports = $resource('http://myurl.com/app_dev.php/:action',
{action:'dailyreports', appid:'@appid', begindate:'@begindate', enddate:'@enddate'});
$scope.loadData = function() {
$scope.dailyreportsResults = $scope.dailyReports.get({appid:$('#sel-apps').val(), begindate:$('#fecha-inicial').val(), enddate:$('#fecha-final').val()});
//it works!!!!
};
$scope.iterate = function() {
for (i=0; i < $scope.dailyreportsResults.data.length; i++){
$scope.periodUnits += $scope.dailyreportsResults.data[i].units;
console.log($scope.periodUnits);
//It doesnt work :(
}
};
index.html
ng-repeat="data in dailyreportsResults.data"
{{data.countryName}}
{{data.units}}
我做错了什么?
谢谢大家!
最佳答案
我不确定您的数据是什么样的,但也许您应该使用“for in”而不是递增数组。
$scope.iterate = function() {
for (x in $scope.dailyreportsResults.data){
$scope.periodUnits += $scope.dailyreportsResults.data[x].units;
console.log($scope.periodUnits);
}
};
另外,我认为你的 ng-repeat 应该附加到一个元素上。
<div ng-repeat="data in dailyreportsResults.data">
{{data.countryName}}
{{data.units}}
</div>
关于javascript - 使用 AngularJS ngResponse 从 API 迭代 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15121261/