2

嗨,我正在 angularjs 中构建一个聊天应用程序,我希望聊天框自动向下滚动。我正在使用我放入指令的这个例子:http: //jsfiddle.net/atRkJ/

它按原样工作,但是当我将它与 ng-repeat 一起使用时,它不起作用。

.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>

指令.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

1 回答 1

4

当您调用代码时:

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

您的ng-repeat 尚未运行并完成其渲染 =>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>

scrollIf现在可以在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); 
        });
    }
   }
  });

演示

于 2013-11-10T04:04:47.567 回答