Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to jump to anchor in angular's partial view?

Tags:

angularjs

I have many items in a long listview. How can my users jump to (i.e. bookmark) to a specific item by visiting mypage.html#the_item_id ?

Actually, it can when I use inline view [Sample 1], but not when I use partial view [Sample 2]. Is there a bug in the latter case, or must I use any workaround?

Thanks in advance!

Sample 1: You can visit page.html#a100 to see item 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>

Sample 2: Can NOT visit page2.html#a100 to see item 100, WHY? ::

<!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>

And this is the scroll_view.html needed by sample 2::

<div>
  <ul>
    <li ng-repeat="i in items"><a id='a{{i.id}}'>{{i.id}}</a></li>
  </ul>
</div>
like image 740
RayLuo Avatar asked Dec 09 '12 05:12

RayLuo


1 Answers

You have to use autoscroll attribute on ng-include.

Check the docs here: http://docs.angularjs.org/api/ng.directive:ngInclude

autoscroll(optional) – {string=} – Whether ngInclude should call $anchorScroll to scroll the viewport after the content is loaded. If the attribute is not set, disable scrolling. If the attribute is set without value, enable scrolling. Otherwise enable scrolling only if the expression evaluates to truthy value.

So in your case:

<div ng-include="'scroll_view.html'" autoscroll></div>
like image 92
matys84pl Avatar answered Nov 15 '22 08:11

matys84pl