Angular with倍数$ anchorScroll

时间:2016-10-19 11:31:41

标签: javascript angularjs

我正在使用angular $anchorScroll并且它工作正常,唯一的问题是:我将在页面中有100个链接,那么使我的角度代码清洁的最佳方法是什么?没有为每个锚链接创建一个函数?

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();
     };

    }]);

1 个答案:

答案 0 :(得分:2)

您可以将参数传递给模板中调用的函数。

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

然后在视图中:

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