AngularJS - how to override directive ngClick

Simcha picture Simcha · Aug 24, 2013 · Viewed 28k times · Source

I want to override directive ng-click: to some make some $rootscope changes before each execution of ng-click. How to do it?

Answer

Eric Chen picture Eric Chen · Apr 22, 2014

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=preview I wrote a sample that removed angular built-in ng-click and add a customized ngClick