3

鉴于此标记:

<li ng-repeat="i in items" ng-attr-id="id-{{i}}">{{i}}</li>

注入$anchorScroll(使其被实例化),如果它与 url 中的哈希匹配,将导致窗口滚动到绑定的 id,因此/#id-4将在加载时滚动到。

.controller('myCtrl', function($scope, $location, $timeout, $anchorScroll) {
  $scope.items = [1,2,3,4];
})

出乎意料的是,如果$scope绑定是异步加载的,$anchorScroll则不会自动或通过$anchorScroll()随时调用手动工作,即使在我可以验证 id 是否已设置的指令中也是如此。这让我很困惑。

Demo here(注释/注释初始 $scope 绑定)。

这是我想出的,但似乎应该有一种更自然的方式使用$anchorScroll. 事实上,它在演示中有效,但奇怪的是在我的项目中不起作用。

.directive('anchorScrollToId', function($location) {
  
  var directive = {
    link: function($scope, $element, $attrs) {
      if ($location.hash() === $attrs.id) {
        $element[0].scrollIntoView();
      }
    }
  };
  
  return directive;
  
})

我的指令演示在这里。

这个问题肯定比看起来更多。

更新

在进一步调查中,问题可能是由于ui-router它的默认autoscroll行为造成的。我一直无法克服这个问题。

4

0 回答 0