Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question

2 Answers

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);
    });
share|improve this answer
 
I need to get this data in script. Is there another way to fetch it? –  Mariola Jul 18 at 21:58
 
Zhoutuo Yang's approach will work. Also you could use $http object to send your request and provide a callback function that accesses Carriers.carrier –  Hippocrates Jul 19 at 13:20
 
I've updated my answer with more detail on using $http and a callback. –  Hippocrates Jul 19 at 14:23

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.