简体   繁体   English

我如何在控制器中使用angular.forEach循环遍历返回的Resource对象数据

[英]how can I loop through returned Resource object data using angular.forEach loop in controller

I came across a similar scenario , but my attempts failed because undefined was always returned and kept on getting error after error in the console. 我遇到了类似的情况 ,但是我的尝试失败了,因为始终返回undefined,并在控制台中不断出现错误。

The data is retrieved from the openweathermap API using the angular $resource factory. 使用角度$ resource工厂从openweathermap API检索数据。 I understand that i can target and get some of the data i need in the view using ng-repeat but what I also want to break down this data in the controller and access some of the keys and values. 我知道我可以使用ng-repeat定位并获取视图中所需的一些数据,但是我也想在控制器中分解此数据并访问一些键和值。 When I console.log($scope.weatherResult) variable that holds the data retrieved from the api I get a Resource object in the console. 当我用console.log($scope.weatherResult)变量保存从api检索到的数据时,我在控制台中得到一个Resource对象。

How can I go about looping through this object to retrieve the data I need. 我该如何遍历此对象以检索所需的数据。 Its basically objects within objects within arrays. 它的对象基本上是数组内的对象。 In the view ng-repeat does wonders to get this data but in the controller I don't know how to retrieve it. 在视图中ng-repeat确实想获取此数据,但在控制器中我不知道如何获取它。 For example if I console.log($scope.weatherResult.city) or console.log($scope.weatherResult.list) the result in the console is always undefined. 例如,如果我用console.log($scope.weatherResult.city)console.log($scope.weatherResult.list) ,则控制台中的结果始终是不确定的。

Now the data I want to retrieve is within the list array - two days worth of data, but the first object list[0].temp has temperature figures, I want to calculate the sum of those figures and divide it and get the average so I can store it in another variable in the controller and output it in the view. 现在我要检索的数据在列表数组中-值得两天的数据,但是第一个对象列表[0] .temp有温度数字,我想计算这些数字的总和并将其除以得到平均值,因此我可以将其存储在控制器的另一个变量中,并在视图中输出。

I'm not sure if im taking a long route here, but i've been in similar situations before but managed to get away with it using the ng-repeat in the view. 我不确定我是否在这里走了很长的路,但是我之前也曾遇到过类似的情况,但是在视图中使用ng-repeat设法摆脱了它。 I need to learn how to do this. 我需要学习如何做到这一点。

Is it possible to loop through the resource object using angular.forEach() function and get the data in the temp object? 是否可以使用angular.forEach()函数遍历资源对象并在temp对象中获取数据? I have attached an image for reference. 我已附上图片以供参考。 I am still learning and gaining experience with JavaScript and angular in particular. 我仍在学习JavaScript,特别是在angular方面,并获得经验。

角资源循环

$scope.temp = []
angular.forEach(list[0].temp, function(value,key){
  $scope.temp.push(value);
})

See if this helps you. 看看这是否对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM