'I have a JSON data structure
[
{
"title" :"a1",
"id" :"b1",
"name" :"c1"
},
{
"title" :"a2",
"id" :"b2",
"name" :"c2"
}
]
I am accessing is as an external JSON and parsed through a factory method. I want it to assign it to a javascript variable in my controller.
function Control($scope,data)
{
var e=data.query(); /* getting the external JSON data */
alert(e[0].title);
}`
It says that e[0] is undefined. Is there any other way I can assign it to a javascript variable and then traverse thru it. Please help. '
Most likely, @Marty is correct. If you are using the query() method from the $resource service, it is asynchronous. This will likely do what you want:
Okay, so $resource can be confusing like this... It immediately gives you a reference to the return object, but doesn't update the object until the asynchronous AJAX call returns... so...
If you put your return value from data.query() in a property on $scope, since it's $watched when you bind it in your view, you'll see it update. HOWEVER, if you're just trying to alert it, it will alert the value before it's been updated.. again because of the async aspect of $resource.
Otherwise, you can get the value the way that @MarkRajcok has shown in his answer.
Here is a psuedo-code illustration of ways you can use $resource query();
This is all done so the object(s) returned can have functions pre-instantiated on them like $save(), etc.