javascript - 自动滚动 AngularJS 似乎不起作用

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

嗨,我正在用 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);
    }
   }
  });

有什么帮助吗?谢谢

最佳答案

当你调用代码时:

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>

现在可以在 ng-repeat 完成时通知您的 scrollIf 指令

.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

关于javascript - 自动滚动 AngularJS 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19885969/

相关文章:

javascript - 嵌套 HTML 表标签被删除

javascript - jquery 效果后边距和填充重置

angularjs - Sonarqube - 排除一组特定文件

javascript - 需要正则表达式来匹配字符串开头的特殊字符

javascript - 在Typescript中使用异步方法链接(只是找到了解决方案)

jquery - 500 内部服务器错误 ASP.NET

get - 如何使用AngularJS删除GET参数?

javascript - 在 angularjs 按钮上使用条件的更 Eloquent 方式

javascript - 为 SelectField 显示空白菜单项的正确方法是什么(material-ui,react)

javascript - += 的异步函数