0

I am trying to track button clicks a user performs on a page/view. I am trying to get the element idwhich was clicked.

Is there a way to do this without having to tie a function or directive to each element?

4
  • 1
    Would this be what you're looking for? Maybe not the directive proposed by Ben, but what you find in the first comment by Fritz. Commented May 29, 2014 at 17:51
  • @Jonathan. I have tried this already, but what I am looking for is the element name of the click. I will update the question. Commented May 29, 2014 at 17:58
  • Well, this is a very interesting problem. I don't know if angular is actually capable of solving it. I agree with callmekatootie that it does appear to be a problem for JQuery... If, however, I find a solution in angular, I'll definitely share it! I'm currently working on an website analytic tool that would benefit from the solution to this question! Commented May 29, 2014 at 18:11
  • 1
    What are you trying to do with the id? When you add a click handler to the document you can just get the id by doing event.target.id. See this plunker Commented May 29, 2014 at 20:04

1 Answer 1

1

ng-controller and ng-click

HTML:

<body ng-controller="MyController" ng-click="go($event)">
  <div id="box1">
    <div id="box2">
      <div id="box3"></div>
    </div>
  </div>
</body>

JS:

$scope.go = function(e) {
  var clickedElement = e.target;
  console.log(clickedElement);
  console.log(clickedElement.id);
};

Demo: http://plnkr.co/edit/1O6pCVrvgu7Bl8b6TlPF?p=preview

Directive:

HTML:

<body my-directive>
  <div id="box1">
    <div id="box2">
      <div id="box3"></div>
    </div>
  </div>
</body>

JS:

app.directive('myDirective', function () {

  return {
    link: function (scope, element, attrs) {

      element.bind('click', function (e) {
        var clickedElement = e.target;
        console.log(clickedElement);
        console.log(clickedElement.id);
      });
    }
  }
});

Demo: http://plnkr.co/edit/eevnMFu2YBj3QqRraeZh?p=preview

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.