Raduken Raduken - 1 month ago 19
AngularJS Question

Angular with multiples $anchorScroll

I am using angular

$anchorScroll
and it is working perfect, the only problem is: i will have 100 links in the page, so what is the best way to make my angular code clean? without create a function for every anchor link?

html:

<div id="scrollArea" ng-controller="ScrollController">
<a ng-click="gotoBottom()">Go to bottom</a>
<a id="bottom"></a> bottom!
</div>

<div id="scrollArea" ng-controller="ScrollController">
<a ng-click="gotoHeader()">Go to header</a>
<a id="header"></a> header!
</div>

<div id="scrollArea" ng-controller="ScrollController">
<a ng-click="gotoMid()">Go to mid</a>
<a id="mid"></a> mid!
</div>


script.js

angular.module('anchorScrollExample', [])
.controller('ScrollController', ['$scope', '$location', '$anchorScroll',
function($scope, $location, $anchorScroll) {
$scope.gotoBottom = function() {
$location.hash('bottom');
$anchorScroll();
};
$scope.gotoMid = function() {
$location.hash('mid');
$anchorScroll();
};

$scope.gotoHeader= function() {
$location.hash('header');
$anchorScroll();
};

}]);

Answer

You can pass parameter to function invoked in template.

 angular.module('anchorScrollExample', [])
 .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
      function($scope, $location, $anchorScroll) {
          $scope.goto = function(anchor){
              $location.hash(anchor);
              $anchorScroll();
         }
}]);

Then in view:

<div id="scrollArea" ng-controller="ScrollController">
  <a ng-click="goto('header')">Go to header</a>
  <a id="header"></a> header!
</div>