【问题标题】:anchorScroll does not execute in controller with ng-repeat?anchorScroll 不在控制器中使用 ng-repeat 执行?
【发布时间】:2016-10-05 16:06:58
【问题描述】:

我想我已经发现了一些关于 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 事件可以绑定...)

【问题讨论】:

    标签: html angularjs angularjs-ng-repeat ng-repeat anchor-scroll


    【解决方案1】:

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

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

    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

    【讨论】:

    • 你是明星!不错的干净解决方案 - 正是我想要的 - 谢谢 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    • 2016-05-20
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    相关资源
    最近更新 更多