Reputation: 249
I am trying to get data from json data so i write this:
app.factory('data', function($resource) {
return $resource('mock/plane_urls.json', {}, {
getTreeData: { method: 'GET', isArray: false }
})
})
and then using:
data.getTreeData.Carriers.Carrier;
Where Carriers is the first node in json file. but it doesnt work ;/ I got error
Error: data.getTreeData.Carriers is undefined
Upvotes: 1
Views: 1463
Reputation: 2540
You are trying to reach into the Carriers
object before it is fetched. Before the data comes back, Carriers is just an empty object.
You could do something like $scope.carriers = data.getTreeData();
and then in your view have an element with ng-repeat="carrier in carriers"
The idea behind $resource is that you get an empty object, so the view renders nothing. When the request is complete, the empty object is replaced and the view is re-rendered with the data automatically.
You could also use the $http service like so and provide a callback function that executes once the data is fetched.
$http.get('mock/plane_urls.json').then(function(data){
carrier = data.Carriers.Carrier
});
BUT! should break this into a service and a controller though. Just have the service getTreeData
return the promise object like so: return $http.get('mock/plane_urls.json');
and then in your controller call it with then() and provide the callbacks for success and error:
getTreeData.then(
function(data){
carrier = data.Carriers.Carrier;
},
function(err){
console.log("Error: " + err);
});
Upvotes: 4
Reputation: 342
You can use $scope.$watch to watch the value of the data.getTreeData. When new data comes in, the callback will be called, then, you can get your data you want.
http://docs.angularjs.org/api/ng.$rootScope.Scope
Upvotes: 1