2012-12-09 27 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); 
    })