1

我想我已经确定了一些关于 ng-repeat 运行时间的奇怪 AngularJS1 行为,因此与控制器执行的时间冲突。

我的控制器自动向下滚动到一个 html 锚 ID: $anchorScroll('html_id');

这适用于静态 html ( static html plunker )

<div id="hello1">Hello1 </div>

但是如果控制器在 ng-repeat ( ng-repeat plunker )生成的 div 上调用它,则 anchorScroll 似乎不起作用

 <div id="{{ITEM.slug}}" ng-repeat="ITEM in LIST">{{ITEM.slug}}</div>

注意:: ng-repeat 上的 anchorScroll 可以通过按钮正常工作,但我希望它在加载时自动滚动...

(我也尝试过使用 ng-init= 来调用滚动函数,但同样的时间问题 - 所以它无法找到锚点......即使在 ng-repeat 之后编码)

任何想法/解决方法?

(似乎没有任何 ng-repeat 事件可以绑定...)

4

1 回答 1

1

为此,必须在摘要循环之后$anchorScroll执行,以便实际呈现项目。

实现这一点的最简单方法是使用$timeout第二0个延迟,这会创建一个将被解决的承诺。有了0延迟,promise 将在当前摘要周期完成后处理,而不是立即处理。

testApp.controller('testCtrl', function($scope, $anchorScroll, $timeout) {
  $scope.LIST = [{
    "slug": "hello1"
  }, {
    "slug": 'hello2'
  }, {
    "slug": 'hello3'
  }];

  $timeout(function() {
    $anchorScroll('hello3');
  }, 0);
});

https://plnkr.co/edit/53hlGNig7eozlm1vqkQL?p=preview

于 2016-10-05T16:32:46.750 回答