滚动 AngularJS ngRepeat with Ajax 加载数据

Scroll AngularJS ngRepeat with Ajax loading data

首先是一个小插曲:http://embed.plnkr.co/C866y3LHCE7QfBGuFQPQ/preview

所以在这里我通过 Ajax 获得一组 posts 并使用 ngRepeat 显示它们。然后(当 post 完成渲染时)我想将页面滚动到特定的 post(假设 post №18)。看起来很简单,但我无法让它工作。

问题似乎是angular在收到Ajax的数据后找不到post,所以position()scrollTop() 功能不起作用。

您必须等到使用新模型更新视图后,使用 $timeout 等待 0 毫秒在 DOM 准备就绪后立即滚动

plunkr

  $scope.getPosts = function() {
    $http.get(data_url).success(function(data){
      $scope.posts = data;
      $timeout(function() {
        var post = $('#pid_18');
        console.log('pid_18', post);
        $('body').scrollTop(post[0].offsetTop);
      }, 0);
    });

我认为问题是渲染没有完成,如果你有 2 个元素,它可以工作,但不能用 1000。

所以最好的方法是知道渲染何时完成,相关的 post :

Calling a function when ng-repeat has finished