如何在角度的局部视图中跳转到锚点?

Ray*_*Luo 6 angularjs

我在很长的列表视图中有很多项目.我的用户如何通过访问mypage.html#the_item_id跳转到(即书签)特定项目?

实际上,它可以在我使用内联视图[样本1]时使用,但在使用局部视图[样本2]时则不行.在后一种情况下是否存在错误,或者我必须使用任何解决方法吗?

提前致谢!

示例1:您可以访问page.html#a100查看项目100 ::

<!doctype html>
<html ng-app>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
    <script>
        function MainCtrl($scope){
            $scope.items = [];
            for(var i=0; i<200; i++){$scope.items.push({id: i})}
        }
    </script>
  </head>
  <body ng-controller='MainCtrl'>
    <div>
      <ul>
        <li ng-repeat="i in items"><a id='a{{i.id}}'>{{i.id}}</a></li>
      </ul>
    </div>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

示例2:无法访问page2.html#a100查看项目100,为什么?::

<!doctype html>
<html ng-app>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
    <script>
        function MainCtrl($scope){
            $scope.items = [];
            for(var i=0; i<200; i++){$scope.items.push({id: i})}
        }
    </script>
  </head>
  <body ng-controller='MainCtrl'>
    <div ng-include="'scroll_view.html'"><!-- MUST use "'...'" notation here --></div>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

这是样本2所需的scroll_view.html ::

<div>
  <ul>
    <li ng-repeat="i in items"><a id='a{{i.id}}'>{{i.id}}</a></li>
  </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

mat*_*4pl 5

您必须在ng-include上使用autoscroll属性.

查看这里的文档:http://docs.angularjs.org/api/ng.directive:ngInclude

autoscroll(可选) - {string =} - ngInclude是否应该在加载内容后调用$ anchorScroll来滚动视口.如果未设置该属性,请禁用滚动.如果设置的属性没有值,则启用滚动.否则,仅在表达式求值为truthy值时才启用滚动.

所以在你的情况下:

<div ng-include="'scroll_view.html'" autoscroll></div>
Run Code Online (Sandbox Code Playgroud)