为什么我的控制器属性'未定义'当我给它分配$resource query()的结果时

Why is my controller property 'undefined' when I assign it the result of $resource query()?

本文关键字:query resource 结果 分配 属性 控制器 我的 未定义 为什么      更新时间:2023-09-26

有一个JSON数据结构:

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

我正在访问的是一个外部JSON和通过工厂方法解析。我想把它赋值给控制器中的Javascript变量。

 function Control($scope,data)
 {
 var e=data.query();   /* getting the external JSON data  */
 alert(e[0].title);    
}

表示e[0]未定义。有没有其他方法可以把它赋值给Javascript变量然后遍历它?请帮助。

@Marty很可能是正确的。如果您正在使用来自$resource服务的query()方法,则它是异步的。这可能是您想要的:

data.query( function( data ) {
  var e = data;
  alert(e[0].title);
});

好的,那么$resource可能像这样令人困惑…它立即为您提供对返回对象的引用,但直到异步AJAX调用返回才更新对象……所以…

如果你把data.query()的返回值放在$scope的属性中,因为当你在视图中绑定它时,它是$守望的,你会看到它更新。然而,如果你只是想提醒它,它会在更新之前提醒这个值。还是因为$resource的异步特性。

否则,您可以通过@ markrajcock在他的答案中显示的方式获得值。

下面是使用$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;
     });
});

这样做是为了使返回的对象可以在其上预先实例化函数,如$save()等。