[英]how do I access child elements of JSON in the controller in Angular JS
I don't understand how to wait for the resource call to finish before assigning the data.properties to $scope in my controller. 我不明白如何在我的控制器中将data.properties分配给$ scope之前等待资源调用完成。
here is my confusion: 这是我的困惑:
i have a resource call that returns this: 我有一个资源调用,返回此信息:
[
{
"PreAlertInventory": "5.000000",
"SharesInInventory": "3.000000",
"TotalSharesSold": "2.000000",
"TotalMoneySharesSold": "18.000000",
"TotalSharesBought": "0.000000",
"TotalShareCost": "0.000000",
"EstimatedLosses": "0.000000"
}
]
here is the applicable code from the controller: 这是来自控制器的适用代码:
$scope.alertSwap = function () {
var data = Data.query(); // gets the data. works as expected
//$scope.test = data; //works as expected. can access data and properties in template
$scope.test = data.TotalMoneySharesSold; //does not work. is empty???
}
i can access the array and its properties from the template BUT not from inside the controller. 我可以从模板BUT访问数组及其属性,而不是从控制器内部访问。
How do I access the child elements from inside the controller that called the resource? 如何从调用资源的控制器内部访问子元素?
http://plnkr.co/edit/JnLqq4v7lKlYOHg85Jma?p=preview http://plnkr.co/edit/JnLqq4v7lKlYOHg85Jma?p=preview
I needed to assign a callback to the resource call, and assign the elements from within the function: 我需要为资源调用分配一个回调,并从函数中分配元素:
$scope.data = Data.query(myParams, function(data) {
$scope.test = data[0].TotalSharesBought;
});
As said above it is likely you are fetching those data async. 如上所述,您可能正在获取这些数据异步。 I updated your code to support promise (which makes your code async and may not fit with the rest of the application by the way).
我更新了您的代码以支持promise(这会使您的代码异步,并且可能不适合应用程序的其余部分)。
$timeout
simulates an async call. $timeout
模拟异步调用。 In your factory service
: 在您的
factory service
:
var deferred = $q.defer();
$timeout(function() {
return deferred.resolve(data);
}, 100); // set it to zero to return immediately
return deferred.promise;
In your controller
call you factory factory method query()
and hook the response with then
, which is the promise
part of the snippet: 在您的
controller
调用工厂工厂方法query()
并使用then
挂钩响应,这是片段的promise
部分:
Data.query().then(function(response) {
$scope.test = response[0].TotalMoneySharesSold;
});
http://plnkr.co/edit/SGGCVS?p=preview http://plnkr.co/edit/SGGCVS?p=preview
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.