2015-10-26 50 views
4

我有一個簡單的指令,從服務加載評論(commentsService)一個初始化函數:使用ng-init調用當指令被加載

'use strict'; 

angular.module('mean.rank') 
    .directive('commentList', function(CommentsService, Global) { 
     return { 
      restrict: 'E', 
      templateUrl: 'rank/views/comments-list.html', 
      replace: false, 
      link: function($scope, element, attrs) { 
       //accessing the ad info : console.log("ADD " , $scope.ad); 
       $scope.comments = []; 

       $scope.loadComments = function() { 
        console.log("in loadComments"); 
        var adID = {}; 
        adID.ad_ID = $scope.ad.nid; 
        console.log("calling services.getComments function with " , adID.ad_ID); 
        CommentsService.getComments(adID.ad_ID) 
         .then(function (response) { 
          angular.forEach(comment in response) 
          $scope.comments.push(comment); 
         }); 


       }; 


      } 
     } 
    }) 

加載的意見應該被加載到列表(templateUrl內)然後加載服務(如果需要,我會添加代碼)。

<div ng-init="loadComments()"> 
    <ul class="media-list comment-detail-list" > 
     <li class="media" ng-repeat="comment in comments" > 
      <article> 
       <div class="pull-left comment-info"> 
        <a href="#" class="author">{{ comment.author }}</a><br /> 
        <time>{{ comment.datePublished | date:"MM/dd/yyyy" }}</time> 
       </div> 
       <div class="media-body"> 
        <div class="comment-body"> 
         <p>{{ comment.comment }}</p> 
        </div> 
       </div> 
      </article> 
     </li> 
     <li>Debugger</li> 
    </ul> 
</div> 

該指令在其範圍內loadCommets()功能,但它不會被觸發。 感謝您的幫助!

回答

4

我建議把函數調用放在鏈接函數本身而不是ng-init中。

angular.module('mean.rank') 
    .directive('commentList', function(CommentsService, Global) { 
     return { 
      ... 
      link: function($scope, element, attrs) { 
       //accessing the ad info : console.log("ADD " , $scope.ad); 
       $scope.comments = []; 

       $scope.loadComments = function() { 
        ... 
       }; 

       $scope.loadComments(); 
      } 
     } 
    }) 

編輯:順便說一句,你的forEach語法是錯誤的。它應該是

angular.forEach(response, function(comment){ 
    $scope.comments.push(comment); 
}); 
+0

它的工作原理!但它會在列表顯示給用戶之前啓動$ scope.comments數組嗎? –

+0

您可以始終假定UI會在典型的基於ajax視圖中的數據之前加載。如果您想在數據加載之前隱藏視圖的某些部分,則需要使用ng-show/ng-hide,直到數據可用。 – Icycool