为什么我的控制器属性 - “未定义”当我为它分配$资源查询结果()? [英] Why is my controller property 'undefined' when I assign it the result of $resource query()?

查看:155
本文介绍了为什么我的控制器属性 - “未定义”当我为它分配$资源查询结果()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 [
{
"title"  :"a1",
"id"     :"b1",
"name"   :"c1"
},
{
"title"  :"a2",
"id"     :"b2",
"name"   :"c2"
}
 ]       


我访问是作为外部JSON,并通过工厂方法解析。我希望把它分配给我的控制器javascript变量。


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);    

}`


它说,E [0]是不确定的。有没有我可以把它分配给一个JavaScript变量,然后遍历直通任何其他方式。请帮忙。


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. '

推荐答案

好了,$资源可能会造成混淆这样的...它马上给你返回的对象的引用,但直到不更新对象AJAX异步调用返回...所以...

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...

如果你把你的返回值从data.query()在属性上$范围,因为它是$看着,当你在你的视图绑定,你会看到它进行更新。不过,如果你只是想提醒它,它将它的更新前,因为$资源的异步方面的提醒值..一次。

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.

另外,你可以得到的值@MarkRajcok在他的回答表现出的方​​式。

Otherwise, you can get the value the way that @MarkRajcok has shown in his answer.

下面是一个方法,你可以使用$资源查询()一psuedo- code说明;

Here is a psuedo-code illustration of ways you can use $resource query();

app.controller('FooCtrl', function($scope, $resource) {
     var Bar = $resource('/Bar/:id', {id: '@id'});

     // here, we get the result reference and stick it in the scope,
     // relying on a digest to update the value on our screen.
     $scope.data = Bar.query();

     //OR

     //here we already have a reference.
     var test = Bar.query(function() {
          //in here, test has been populated.
          $scope.data2 = test;
     });
     alert(test); //not populated here, yet.

     //OR

     Bar.query(function(x) {
          $scope.data3 = x;
     });
});

这是所有这样做的目标(S)返回可以有功能pre-实例化他们喜欢$保存()等。

This is all done so the object(s) returned can have functions pre-instantiated on them like $save(), etc.

这篇关于为什么我的控制器属性 - “未定义”当我为它分配$资源查询结果()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆