1

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

2 Answers 2

4

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);
    });
Sign up to request clarification or add additional context in comments.

3 Comments

I need to get this data in script. Is there another way to fetch it?
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
I've updated my answer with more detail on using $http and a callback.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.