[angularjs] Using ng-click vs bind within link function of Angular Directive

In the link function, is there a more "Angular" way to bind a function to a click event?

Right now, I'm doing...

myApp.directive('clickme', function() {   
  return function(scope, element, attrs) {
    scope.clickingCallback = function() {alert('clicked!')};
    element.bind('click', scope.clickingCallback);   
} });

Is this the Angular way of doing it or is it an ugly hack? Perhaps I shouldn't be so concerned, but I'm new to this framework and would like to know the "correct" way of doing things, especially as the framework moves forward.

This question is related to angularjs angularjs-directive

The answer is


myApp.directive("clickme",function(){
    return function(scope,element,attrs){
        element.bind("mousedown",function(){
             <<call the Controller function>>
              scope.loadEditfrm(attrs.edtbtn); 
        });
    };
});

this will act as onclick events on the attribute clickme


I think it is fine because I've seen many people doing this way.

If you are just defining the event handler within the directive, you do not have to define it on the scope, though. Following would be fine.

myApp.directive('clickme', function() {
  return function(scope, element, attrs) {
    var clickingCallback = function() {
      alert('clicked!')
    };
    element.bind('click', clickingCallback);
  }
});

Shouldn't it simply be:

<button ng-click="clickingCallback()">Click me<button>

Why do you want to write a new directive just to map your click event to a callback on your scope ? ng-click already does that for you.


You should use the controller in the directive and ng-click in the template html, as suggested previous responses. However, if you need to do DOM manipulation upon the event(click), such as on click of the button, you want to change the color of the button or so, then use the Link function and use the element to manipulate the dom.

If all you want to do is show some value on an HTML element or any such non-dom manipulative task, then you may not need a directive, and can directly use the controller.


In this case, no need for a directive. This does the job :

<button ng-click="count = count + 1" ng-init="count=0">
  Increment
</button>
<span>
  count: {{count}}
</span>

Source: https://docs.angularjs.org/api/ng/directive/ngClick