在我的指令内容加载到页面后,如何操作 DOM? [英] How can I manipulate the DOM after my directive's content has been loaded on the page?

查看:25
本文介绍了在我的指令内容加载到页面后,如何操作 DOM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写自己的聊天界面,以帮助我更好地理解 angularJs 和 socket.io.

I am writing my own chat interface, to help me better understand angularJs and socket.io.

我的聊天窗口已修复,溢出设置为自动.我正在使用以下指令来操纵 DOM 进行滚动,以便将每条消息推送到模型数组上时,它将在窗口底部可见.

My chat window is fixed, with overflow set to auto. I am using the following directive to manipulate the DOM to scroll, so that as each message is pushed onto the model array, it will be visible at the bottom of the window.

app.directive('plnkScroll', [function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
              angular.element(element)[0].scrollIntoView();
        }
    };
}]);

理论上,这是有效的.但是,如果消息的长度足以占据多于一行,则它不会滚动以确保整行都清晰可见.

In theory, this works. However, if the message is long enough to take up more than one line, it does not scroll so that the entire line is clearly visible.

这是因为 scrollIntoView 方法正在 DOM 上执行,而角度表达式尚未计算(在这种情况下,{{item.text}})

This is because the scrollIntoView method is being executed on the DOM while the angular expression has yet to be evaluated (in this case, {{item.text}})

是否可以在评估 Angular 表达式并将模型数据注入 DOM 之后执行此函数?

Is it possible to execute this function after the Angular expression has been evaluated and the model data has been injected into the DOM?

这是我的 plunker,以帮助说明我在做什么.

here is my plunker, to help illustrate what I am doing.

附言使用 jQuery 不是我的选择,我想以角度方式"做事.

p.s. using jQuery is not an option for me, I would like to do things "the angular way".

推荐答案

你可以在指令元素追加到父元素后使用 $timeout 执行你的代码.

your can use $timeout excute your code after directive element append to parent.

app.directive('plnkScroll', ['$timeout',function ($timeout) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
              $timeout(function(){
                angular.element(element)[0].scrollIntoView();
              },50);
            }
        };
    }]);

这篇关于在我的指令内容加载到页面后,如何操作 DOM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆