AngularJS - how to override directive ngClick AngularJS - how to override directive ngClick angularjs angularjs

AngularJS - how to override directive ngClick


Every directive is a special service inside AngularJS, you can override or modify any service in AngularJS, including directive

For example remove built-in 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 support multiple directives to the same name so you can register you own ngClick Directive

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

check out http://plnkr.co/edit/U2nlcA?p=previewI wrote a sample that removed angular built-in ng-click and add a customized ngClick


You can't override AngularJS built-in directives. However, you can define multiple directives with the same name and have them executed against the same element. By assigning appropriate priority to your directive, you can then control whether your directive runs before or after a built-in directive.

This plunker shows how to build an ng-click directive that executes before the built-in ng-click does. The code is also shown below. When clicking the link, the custom ng-click will run first, then the built-in ng-click does.

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!')    }  })