2012-12-09 73 views
6

我有很多项目在一个很长的列表视图。我的用户如何通过访问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> 

示例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> 

这是样品2 ::

<div> 
    <ul> 
    <li ng-repeat="i in items"><a id='a{{i.id}}'>{{i.id}}</a></li> 
    </ul> 
</div> 
+1

我有完全相同的问题。你有没有找到解决方案?从我发现的问题是,jqlite'element.getElementById'在'scroll'函数中返回null。也许是因为内容不存在于DOM中呢? – NilsH

回答

5

你必须使用自动滚屏在属性所需的scroll_view.html NG-包括。

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

自动滚屏(可选) - {字符串=} - 是否ngInclude应该调用$ anchorScroll内容加载后滚动视口。 如果该属性未设置,请禁用滚动。 如果该属性设置为无值,则启用滚动。 否则仅在表达式评估为真值时启用滚动。

所以你的情况:

<div ng-include="'scroll_view.html'" autoscroll></div> 
+0

感谢您的诀窍!我应该仔细阅读所有的文档。 – RayLuo

+0

我很高兴帮助。你能否选择接受的答案呢? ;) – matys84pl

+0

所以它理论上应该解决这个问题。结果发现问题比我们想象的更复杂。 当我在Chrome 23上测试时,只有内联实现(sample1)按预期工作。使用部分视图时,无论是否使用自动滚动设置,page.html#锚点表示法都无法将我们带到目的地。 Firefox 17中的情况更糟糕,非上述组合作品。我正在使用Windows平台上的AngularJS 1.0.3进行测试。 不知道这只是我自己。所以,只要保持这个问题的开放性,看看别人可能会有什么反馈。无论如何谢谢@ matys84pl。 – RayLuo

1

我认为html5Mode需要设置为true,但我不能肯定。看看这对你的作品(它为我做的,但我只在Chrome 23测试使用文件加载页面:/// ...):

<!doctype html> 
<html ng-app="app"> 
    <head> 
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script> 
    <script src="app.js"></script> 
    <script type="text/ng-template" id="scroll_view.html"> 
     <div> 
     <ul> 
      <li ng-repeat="i in items"><a id='a{{i.id}}'>{{i.id}}</a></li> 
     </ul> 
     </div> 
    </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> 

app.js:

var app = angular.module('app', []). 
    config(function($locationProvider) { 
    $locationProvider.html5Mode(true); 
    })