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