奇怪的Angularjs行为与对象进入服务

时间:2013-08-03 23:50:04

标签: angularjs angularjs-scope angularjs-ng-repeat

我有一个服务,可以定义一个对象。

app.factory('Store', function($http, $q){
  var obj = {
   data : [],
   load:function(params){
       var def = $q.defer();
       var count = 0;
       var nb = 0;
       while(var i<10){
           count++;
           Anotherservice.getData(i).then(function(result){
               obj.data.push(result);
               nb++;
               if(nb==count){
                     def.resolve(obj);
               }
           });
           i++;
       }
       return def.promise();
    }
 }

 return{
   load : function(params){
       var deferred = $q.defer();
       obj.load(params).then(function(dd){
           deferred.resolve(dd);
       }
       return deferred;
   }
 }
});

在我的控制器中,我有

Store.load("abc").then(function(stObj){
  $scope.stObj = stObj;
  console.debug($scope.stObj.data); <--- debug the array with its content correctly
  $scope.stObjData = stObj.data;
  console.debug($scope.stObjData); <--- debug the array with its content correctly
});

在我看来,

{{stObj}} -> displays the obj correctly, with obj.data as a property containing all the results.

{{stObj.data}} -> displays an empty array (while it should display data inside)
{{stObjData}} -> displays an empty array (while it should display data inside)

<div ng-repeat="res in stObj.data">
  {{res}} <-- doesn't display anything
</div>

我被困在这里,我真的不明白发生了什么,因为stdObj显然不是空的,是不是一个bug?

1 个答案:

答案 0 :(得分:0)

创建延迟实例时会创建一个新的promise实例,并且可以通过调用deferred.promise而不是deferred.promise()来检索。我为你创建了一个演示。

Demo on jsFiddle