autoscroll angularjs似乎不起作用

时间:2013-11-10 03:31:16

标签: javascript jquery angularjs angularjs-directive angularjs-ng-repeat

您好我正在angularjs中构建一个chatapp,我希望聊天框能够自动向下滚动。我正在使用这个示例,我将其放入一个指令: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>

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);
    }
   }
  });

有任何帮助吗?感谢

1 个答案:

答案 0 :(得分:4)

当您致电代码时:

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

你的 ng-repeat没有运行并完成 它的渲染还是&gt;返回的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); 
        });
    }
   }
  });

DEMO

相关问题