I don't understand how to wait for the resource call to finish before assigning the data.properties to $scope in my controller.
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.
How do I access the child elements from inside the controller that called the resource?
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;
});
Your data would appear to be returned as an array, try $scope.testTwo = data[0].TotalSharesBought
.
I've updated your Plunkr accordingly.
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).
$timeout
simulates an async call. In your 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:
Data.query().then(function(response) {
$scope.test = response[0].TotalMoneySharesSold;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.