1

AngularJS: How to listen to DOM Events? this answer provided is using ng-click directive. My scenarios is that I want to avoid this approach.

This is my sample code

Here is my attempt.

$('#test').on({
           click: function (e) {
                console.log("test...");
           }
      });
$('#login').on({
           click: function (e) {
                console.log("test...");
           }
      });

JS Fiddle

I need a listener to be implemented which will listen to any click even of the given dom element. any help on this is appreciated.

Community
  • 1
  • 1
Sanath
  • 4,774
  • 10
  • 51
  • 81
  • 1
    I suggest reading AngularJS docs on 'directives'. Really you should avoid DOM handling in Controllers. One suggestion would be to create a simple directive that simply uses event delegation to respond to 'click' events on the parent element you care to delegate to (ie, the body). – SonOfNun Aug 06 '13 at 06:54
  • 10
    Sorry. But, why is `ng-click` not a good fit? http://jsfiddle.net/2nHxs/. – Jonathan Lonowski Aug 06 '13 at 06:54

1 Answers1

4

If you really don't want to use ng-click, you could use a directive and add a simple attribute to you DOM elements

Check this fiddle : http://jsfiddle.net/DotDotDot/ZYdEf/5/

I simply created a directive which bind a click event on the element, then log the click :

directive('clickable', function(){
    return function(scope, elt, attr){
        elt.bind('click', function(e){
            console.log('hello from',elt) 
        })
})

Then, in your HTML it's really easy :

<a href="#" id="test" clickable>Click</a>
<a href="#" id="login" clickable>Log</a>

Have fun

DotDotDot
  • 3,566
  • 2
  • 20
  • 22