$ timeout scrollTop指令在angularJS中不起作用

时间:2016-10-14 09:04:15

标签: javascript html angularjs

我正在尝试在angularJS中进行一次小聊天。我使用div显示我的消息,我希望我的div在页面加载时向下滚动。我创建了一个指令来做到这一点。

我的HTML:

newfac=(2*ctr-1)!

我的角度指示:

<div id="myChat" style="height: 500px; overflow-y: scroll;border: 1px solid #ccc;border-radius: 4px;" scroll-bottom>
    <div ng-repeat='message in chatMessagesArray'><span style="color:green">aaa</span><span> bbb</span></div>
</div>

在控制台上,我看到console.log()的输出为0,所以我知道指令被触发但第二行没有完成......你知道什么是错的吗?在MAC OS X + Chrome / FF上进行测试

1 个答案:

答案 0 :(得分:2)

试试这个。在这里我添加了1秒的超时。页面加载后立即滚动只删除毫秒部分

&#13;
&#13;
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.chatMessagesArray = ["a", "b", "c", "d", "e", "f"];
});
app.directive('scrollBottom', ['$timeout',
  function($timeout) {
    return {
      link: function(scope, element) {
        $timeout(function() {
          $(element).scrollTop($(element)[0].scrollHeight)
        })
      }
    }
  }
]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <div id="myChat" style="height: 500px; overflow-y: scroll;border: 1px solid #ccc;border-radius: 4px;" scroll-bottom>
    <div ng-repeat='message in chatMessagesArray'> <span style="color:green">aaa</span>
      <br>
      <span> bbb</span>
      <br>
      <span style="color:green">aaa</span>
      <br>
      <span> bbb</span>
      <br>
      <span style="color:green">aaa</span>
      <br>
      <span> bbb</span>
      <br>
      <span style="color:green">aaa</span>
      <br>
      <span> bbb</span>
      <br>
      <span style="color:green">aaa</span>
      <br>
      <span> bbb</span>
      <br>
      <span style="color:green">aaa</span>
      <br>
      <span> bbb</span>
      <br>
      <span style="color:green">aaa</span>
      <br>
      <span> bbb</span>
      <br>
      <span style="color:green">aaa</span>
      <br>
      <span> bbb</span>
      <br>
      <span style="color:green">aaa</span>
      <br>
      <span> bbb</span>
      <br>
      <span style="color:green">aaa</span>
      <br>
      <span> bbb</span>
      <br>
      <span style="color:green">aaa</span>
      <br>
      <span> bbb</span>
      <br>
      <span style="color:green">aaa</span>
      <br>
      <span> bbb</span>
      <br>
      <span style="color:green">aaa</span>
      <br>
      <span> bbb</span>
      <br>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;