javascript - AngularJS 指令 - 将滚动条设置在正确的位置

标签 javascript angularjs

正如其他线程中发布的那样,我有这个指令。 我将实现的是,用户向上滚动,战后数据从后端重新加载(在底部的指令中模拟)。 我现在的问题是重新加载数据并添加到 eisting 数组后,如何处理滚动条 - 如何将滚动条设置到它应该在的位置(新加载的数据开始的位置) 是否有可能或概念可以做到这一点。

(function() {
'use strict';

angular
    .module('myProject.common')
    .directive('asScrollTop', asScrollTop);

function asScrollTop() {
    var directive = {
        restrict: 'A',
        scope: { chatMessagesOfUser: '=' },
        link: link
    };
    return directive;

    ////////////

    function link(scope, element, attr) {
        console.log(element);
        element.on('scroll', function() {
          if(element[0].scrollTop <= 0) {

              for(var i = 0; i < 10; i++) {
                  var newChatMessage = {};
                  newChatMessage.color = '#00ff00';
                  newChatMessage.confirmation = false;
                  newChatMessage.id = '57b05e24ce861d23bec293df';
                  newChatMessage.links = null;
                  newChatMessage.messageBody = 'das ist die neue message';
                  newChatMessage.messageUserConnectionId = '57b05e24ce861d23bec293e0';
                  newChatMessage.name = 'Mag. Testname testname';
                  newChatMessage.read = true;
                  newChatMessage.time = '13.08.2016 11:23';
                  newChatMessage.userCreatedMessageId = '"5589929b887dc1fdb501cdba"';

                  scope.chatMessagesOfUser.splice(0, 0, newChatMessage);
              }
              scope.$apply();
          }
        });
      }
}

})();

最佳答案

window.scrollTo 是用于将页面滚动到某个位置的 javascript 函数。 From MDN :

Scrolls to a particular set of coordinates in the document.

Example

window.scrollTo( 0, 1000 );

您可以使用此函数滚动页面,但前提是您知道新数据的 Y 位置。

也许您应该考虑在数据中插入 anchor 标记以用作 scrollTo 的引用点。

关于javascript - AngularJS 指令 - 将滚动条设置在正确的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38944032/

相关文章:

Javascript:在不涉及日期的情况下查找两个 'time' 字符串之间的时间差

php - PHP 中嵌入 MySQL 请求的 Javascript

javascript - 在 Angular.js 中使用 ngRoute 时出现错误

angularjs - 如何隐藏 Angularjs 源代码?

javascript - 如何在此 Angular 2 样本上使用 HTML5 模式?

angularjs - 如何运行 Protractor

javascript - 我需要向函数添加参数吗?

javascript - 使用 Protractor 中的 Typescript,如何确定内部函数的范围以便其他函数可以访问它?

javascript - Mithril js,m.request()循环和concat数组有什么好的方法吗?

angularjs - 在 AngularJS 中使用 ng-pattern 验证电子邮件