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