dabadaba dabadaba - 5 months ago 13
AngularJS Question

How to include anchors to elements placed in a different template?

Say I have the following list in a

sidebar.html
partial:

<div id="players">...</div>
<div ng-include="'partials/courts.html'"></div>

<ul>
<li><a href="#players">Players</a></li>
<li><a href="#courts">Courts</a></li>
</ul>


But the
div#courts
is not in
sidebar.html
but in
partials/courts.html
:

// partials/courts.html
<div id="courts">...</div>


How can I refer to
div#courts
from the list in
sidebar.html
?

Answer

You need to use $anchorScroll

When called, it scrolls to the element related to the specified hash or (if omitted) to the current value of $location.hash(), according to the rules specified in the HTML5 spec.


Add this in your controller:

app.controller('MainCtrl', function($scope, $location, $anchorScroll) {

   $scope.scroll = function(id) {
      $location.hash(id);
      $anchorScroll();
   }

});

Change the links to include ng-click="scroll('<element id>'):

<ul>
  <li><a href="" ng-click="scroll('players')">Players</a></li>
  <li><a href="" ng-click="scroll('courts')">Courts</a></li>
</ul>

Online Demo - https://plnkr.co/edit/54O1NAy3Z7bguRXeSCsO?p=preview