2014-10-28 87 views
0

我有一个简单的控制器与服务作为依赖关系。我试图在resource的承诺解决后填补范围。当我向范围显示数据的范围时,我的ng-repeat不起作用。此外,我正在使用chrome的角度扩展,在该范围(posts)不显示任何数据。我错过了什么?角度资源不填充范围

控制器:

function TimelineController($scope,TimelineService) 
    { 
     $scope.posts = []; 

     $scope.getPosts = function(wall_type,wall_id) { 
      TimelineService.getPosts(wall_type,wall_id).$promise.then(function(result){ 
       $scope.posts = result.response; 
       console.log($scope.posts); // it show correctly the data on console 
      }); 
     } 
    } 

服务

function TimelineService($resource) { 

     var resource = $resource('/timeline/:postId', 
      {postId:"@id"} 
     ); 

     return { 
      getPosts: function(entity,id) 
      { 
       // /timeline?entity=user&id=3 (example url) 
       return resource.get({entity:entity,id:id}); 
      } 
     } 
    }; 

来自服务器的响应是:

{success:true, response:[...]} 

编辑:

我使用的是指令与显示模板ng-repeat

function timeline() { 

     return { 
      restrict: 'E', 
      replace: true, 
      scope: { 
       type: '@', 
       ids: '@', 
       postime: '&' 
      }, 
      templateUrl:"/js/templates/timeline/post-tmpl.html" 
     } 
}; 

所以在我看来:

<div class="col-md-8" ng-controller="TimelineController"> 
<timeline type="user" ids="8" postime="getPosts(wall_type,wall_id)"></timeline> 
</div> 

而且我的模板的短版:

<ol class="timeline" ng-init="postime({wall_type:type,wall_id:ids})"> 
    <li ng-repeat="post in posts"> 
     {{post.poster.fullname}} 
    </li> 
</ol> 
+0

视图在哪里?特别提到'ng-repeat' – Cherniv 2014-10-28 13:43:13

+0

对不起,我编辑我的文章 – Fabrizio 2014-10-28 13:48:52

回答

0

我认为数据需要被应用和消化,因为服务功能不是控制器范围的一部分。

在您的控制器中,在console.log之前或之后运行$scope.$apply()

如果$ apply或$ digest已在进行中,那么您可以用延迟为0的setTimeout包装$scope.$apply(),或者您可以用$scope.$evalAsync()包装它。

+0

感谢您的回答,但添加了'$ scope。$ apply()'抛出这个错误:https://docs.angularjs.org/error/$rootScope/ inprog?p0 = $ digest,但至少现在数据只显示在'角铬检查器'上 – Fabrizio 2014-10-28 13:59:49

+0

我编辑了答案,提供了针对该问题的选项。 – James 2014-10-28 14:41:56

+0

非常感谢,但是我发现了这个问题,因为出于某种原因控制器上的范围对指令不可用,所以我不得不将范围作为指令 – Fabrizio 2014-10-28 15:09:52