AngularJS-如何覆盖ngClick指令



我想重写指令ng-click:以便在每次执行ng-clic之前对$rootscope进行一些更改。怎么做?

每个指令都是AngularJS内的一个特殊服务,您可以覆盖或修改AngularJS中的任何服务,包括指令

例如,移除内置的ngClick

angular.module('yourmodule',[]).config(function($provide){
    $provide.decorator('ngClickDirective', ['$delegate', function($delegate) {
        //$delegate is array of all ng-click directive
        //in this case first one is angular buildin ng-click
        //so we remove it.
        $delegate.shift();
        return $delegate;
    }]);
});

angular支持对同一名称的多个指令,因此您可以注册自己的ngClick指令

angular.module('yourmodule',[]).directive('ngClick',function (){
  return {
    restrict : 'A',
    replace : false,
    link : function(scope,el,attrs){
      el.bind('click',function(e){
        alert('do you feeling lucky');
      });
    }
  }
});

结账http://plnkr.co/edit/U2nlcA?p=preview我写了一个示例,删除了angular内置的ng-click,并添加了一个自定义的ngClick

您不能覆盖AngularJS内置指令。但是,您可以定义具有相同名称的多个指令,并针对同一元素执行这些指令。通过将适当的priority分配给指令,可以控制指令是在内置指令之前运行还是在内置指令之后运行。

这个plunker展示了如何构建一个在内置ng-click之前执行的ng-click指令。代码也显示在下面。单击链接时,将首先运行自定义ng-click,然后运行内置ng-click

index.html

<!DOCTYPE html>
<html ng-app="app">
  <head>
    <script data-require="jquery@1.9.0" data-semver="1.9.0" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.js"></script>
    <script data-require="angular.js@1.0.7" data-semver="1.0.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
    <script src="script.js"></script>
  </head>
  <body ng-controller="MyCtrl">
    <a ng-click="alert()">Click me</a>
  </body>
</html>

script.js

angular.module('app', [])
  .directive('ngClick', function($rootScope) {
      return {
        restrict: 'A',
        priority: 100, // give it higher priority than built-in ng-click
        link: function(scope, element, attr) {
          element.bind('click', function() {
            // do something with $rootScope here, as your question asks for that
            alert('overridden');
          })
        }
      }
  })
  .controller('MyCtrl', function($scope) {
    $scope.alert = function() {
      alert('built-in!')
    }
  })

最新更新