Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - how to override directive ngClick

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

like image 874
Simcha Avatar asked Aug 24 '13 18:08

Simcha


People also ask

Can we create custom directive in AngularJS?

AngularJS allows you to create custom directives with which it becomes easier to encapsulate and simplify DOM manipulation in AngularJS. These directives extend the HTML functionality.

How does directive work in AngularJS?

AngularJS directives are extended HTML attributes with the prefix ng- . The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.


1 Answers

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

like image 103
Eric Chen Avatar answered Sep 17 '22 15:09

Eric Chen