AnchorScroll仅在第二次单击后才有效

时间:2015-04-14 21:20:57

标签: angularjs

我相信我遇到了同样的问题:$anchorScroll and $location only work after second try

我查看了有效的plunker,我已经安排了路由,但它仍然需要两次点击。我使用的是ng-route而不是ui-router。如何防止它单击两次才能让anchorScroll工作?因为第一个想要建立路线而不是滚动到适当的锚点。

点击次数:

<a data-ng-click="gotoRequests()">Requests</a>

这是目的地:

<div id="pendingrequests"></div>

这是我的控制器中的功能:

    $scope.gotoRequests = function() {
        // set the location.hash to the id of
        // the element you wish to scroll to.
        $location.hash('pendingrequests');

        // call $anchorScroll()
        $anchorScroll();
    };

4 个答案:

答案 0 :(得分:9)

我能够使用其中一个答案来解决它:How to handle anchor hash linking in AngularJS

创建以下功能:

$scope.scrollTo = function(id) {
var old = $location.hash();
$location.hash(id);
$anchorScroll();
//reset to old to keep any additional routing logic from kicking in
$location.hash(old);
};

我会这样称呼:

<a href="" data-ng-click="scrollTo('pendingrequests')">Yipee</a>

<div id="pendingrequests"></div>

答案 1 :(得分:1)

最新更新

来自AngularJS 1.4.0 $anchorScroll允许您直接将id作为参数传递,而无需使用哈希更新URL。

点击

<div data-ng-click="gotoRequests(pendingrequests)"> </div>

在控制器

$scope.gotoRequests = function(divId) {  $anchorScroll(divId); }

答案 2 :(得分:0)

我也遇到了与角度1相同的问题,我使用$timeout解决了它。这是我如何做的一个例子

angular.module('app').controller('MyTestController', ['$scope', '$location', '$anchorScroll', '$timeout', function($scope, $location, $anchorScroll, $timeout) {
function scrollToElement (element, offset){
    $timeout(function() {
      $anchorScroll.yOffset = offset; // add extra pixels to scroll initially
      var old = $location.hash();
      $location.hash(element);
      $anchorScroll();
      $location.hash(old);
    });
  }
scrollToElement('element ID', 100);
}]);

答案 3 :(得分:0)

您需要为{300添加$timer,例如:

this.gotoBottom = function(scrollId) { 
    $timeout(function() { 
        $location.hash(scrollId); $anchorScroll(scrollId); 
    }, 300);
}
相关问题