我正在使用 AngularJS 构建一个类似控制台的应用程序。我的要求之一是包含控制台的 div 自动向下滚动。我使用监控内容并相应调整 div 的 scrollTop
属性的指令实现了这一点:
app.directive('autoScroll', function () {
return {
restrict: 'A',
link: function (scope, element, attrs, ctrls) {
var scrollToBottom = function () {
element[0].scrollTop = element[0].scrollHeight;
};
scope.$watchCollection('outputLines', scrollToBottom);
}
};
});
显示行的第一种方法是将 ng-repeat
与无序列表和大括号语法结合使用:
<div auto-scroll id="withHtml" class="list">
<ul>
<li ng-repeat="line in outputLines">{{line.text}}</li>
<li>>> {{currentInput}}</li>
</ul>
</div>
正如您在 this fiddle 的绿色输出区域中看到的那样,效果非常好。 。输入行(以 >>
开头的行始终可见。
但要求之一是在输出行中呈现 HTML。因此,我开始使用 ngSanitize 模块,并从大括号语法切换为使用 ng-bind-html 指令:
<div auto-scroll id="withHtml" class="list">
<ul>
<li ng-repeat="line in outputLines" ng-bind-html="line.text"></li>
<li>>> {{currentInput}}</li>
</ul>
</div>
这会导致输入行始终移出可见区域。正如您在the fiddle mentioned above中的红色输出区域中看到的那样:
两种情况下生成的输出看起来相同。所以这是我的问题:为什么滚动行为会根据我使用大括号语法还是 ng-bind-html 指令而有所不同?
最佳答案
这是一个时间问题。
如果您执行以下操作:
var scrollToBottom = function () {
console.log(element[0].scrollHeight);
element[0].scrollTop = element[0].scrollHeight;
};
您会注意到,经过几次输入后,设置 scrollTop
时的 scrollHeight
会有所不同。
我还没有深入研究源代码来了解导致此问题的原因,但您可以使用 $evalAsync
来确保代码在 Angular 操作 DOM 之后、之前运行浏览器呈现:
var scrollToBottom = function() {
scope.$evalAsync(function() {
element[0].scrollTop = element[0].scrollHeight;
});
};
关于javascript - 为什么 AngularJS 的 ng-bind-html 指令会改变 div 的溢出行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23652993/