2

您好我正在建立一個chatapp在angularjs中,我希望chatbox自動向下滾動。我使用這個例子,我把一個指令:http://jsfiddle.net/atRkJ/autoscroll angularjs似乎並不工作

它的工作原理是,但是當我用它與ng重複它不起作用。

HTML文件

 <ul id="chat" style="height:300px; overflow:auto" scroll-if> 

      <li data-ng-repeat="messageinfo in messages" > 

       <div class="message-date"> 
        {{messageinfo[0]}} 
       </div> 

      </li> 

     </ul> 

directive.js

.directive('scrollIf', function() { 
return{ 
    restrict: "A", 
    link: function(scope, element, attributes) { 
     var chat_height = $('#chat').outerHeight(); 
     console.log(chat_height); 
     $('#chat').scrollTop(chat_height); 
    } 
    } 
    }); 

任何幫助嗎?由於

回答

4

當你調用代碼:

var chat_height = $('#chat').outerHeight(); 
console.log(chat_height); 
$('#chat').scrollTop(chat_height); 

NG重複不運行並完成它的渲染尚未=>的outerHeight返回是不正確的。

ng-repeat完成時,您必須運行您的代碼。要做到這一點,你可以定義另一個指令:

.directive('scrollItem',function(){ 
    return{ 
    restrict: "A", 
    link: function(scope, element, attributes) { 
     if (scope.$last){ // If this is the last item, trigger an event 
      scope.$emit("Finished"); 
     } 
    } 
    } 
}); 

使用它:

<li data-ng-repeat="messageinfo in messages" scroll-item> 

ng-repeat完成

.directive('scrollIf', function() { 
return{ 
    restrict: "A", 
    link: function(scope, element, attributes) { 
     scope.$on("Finished",function(){ //Handle an event when all the items are rendered with ng-repeat 
      var chat_height = element.outerHeight(); 
      console.log(chat_height); 
      element.scrollTop(chat_height); 
     }); 
    } 
    } 
    }); 

DEMO

+0

真棒你scrollIf指令現在可以通知。謝謝 – user1424508