【问题标题】:Why does the ng-bind-html directive of AngularJS changes the overflow behavior of a div?为什么 AngularJS 的 ng-bind-html 指令会改变 div 的溢出行为?
【发布时间】:2014-05-14 11:11:29
【问题描述】:

我正在使用 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 的绿色输出区域中看到的那样,这非常有效。输入行(以&gt;&gt; 开头的行始终可见。

但其中一项要求也是在输出行中呈现 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 指令而有所不同?

【问题讨论】:

    标签: javascript html angularjs scroll ng-bind-html


    【解决方案1】:

    这是时间问题。

    如果您执行以下操作:

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

    演示: http://jsfiddle.net/cBny9/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-05
      • 2015-05-05
      • 1970-01-01
      • 2015-08-09
      • 1970-01-01
      相关资源
      最近更新 更多