Reputation: 5263
I have a service that returns JSON, assume this is the response:
{
"model": 48870,
"id": 20
}
I can do this:
$scope.response = Service.get();
And it will assign the JSON response to $scope.response
. The issue here is I cannot directly access model
or id
via $scope.response.model
or $scope.response.id
, respectively. My workaround for this situation is to define a function in the service's success callback and fetch model
or id
from data
. But this is not very practical considering $scope.response
contains the entire JSON object and should in theory (and the sake of clean code) let me access its children.
Two questions here:
Upvotes: 3
Views: 7218
Reputation: 916
Once the asynchronous HTTP call returns, it is safe to access response's properties directly.
app.controller('MainCtrl', function($scope, $resource) {
$scope.data = $resource('data.json').get(function() {
$scope.loaded = true;
//now it's safe to access $scope.data's properties:
$scope.data.foo = $scope.data.id + ':' + $scope.data.model;
});
});
UI bindings will work automatically.
Upvotes: 1
Reputation: 805
I think what you are looking for is described here:
http://docs.angularjs.org/tutorial/step_05
Upvotes: 0