Angular JS - bind onclick event to all links on page

I have an AngularJS app. There was a requirement for when I should track when a user clicks on an external link ( <a href="http://some-other-site.com/offers">click here for offers</a>

).

Normally in jQuery I would write something like the following:

$(document).on('click', 'a[href^="http://"]', function() {
    // perform tracking here
    return true;
});

      

But I am trying to avoid using jQuery and do Angular stuff. But what is the best way to handle this in pure Angular? I do not want to resort to setting ng-click on all external links as they will constantly change as new functionality is added.

+3


source to share


3 answers


I am late to the party, but I would like to ask your question from a different perspective:

What is the "angular way" in this context?

I asked myself the same questions and I came to the following conclusion:

  • the "angular way" is not the opposite of the "jQuery way" simply because jQuery is not a framework (jQuery is what every developer asks why it is not the default in every browser)
  • I always need to go "angular" when the task is to change model data in an application

In your case, the tracking needs to be added to external links, so I assume that these changes did not affect the data associated with the application. In this case, I would go with the solution that is easiest to maintain (because we all know that later on someone will want to remove the tracking or add another tracking, or both).

1) As mentioned in the comments, there is a clean js way:

var externalLinks = document.querySelectorAll('a[href^="http://"]');
for (i = 0; i < externalLinks.length; ++i) {
    var link = externalLinks[i];
    link.addEventListener('click', function(e) {
        // track me
    });
}

      



http://jsfiddle.net/a7fg217h/1/

2) And another angular solution:

.directive('extLink', function() {
  return {
    restrict: 'A',
    link: function(scope, elem) {
      console.log(elem);
      elem.bind('click', function(e) {
        console.log(e);
      });
    }
  };
})

      

The only difference from the already supplied answer is that you are using this directive as an attribute:

<a ext-link href="http://google.com">Link</a>

      

http://plnkr.co/edit/OhPfEzwDK3j4d17O86oo?p=preview

+1


source


You can set the Directive directly in tag a , all tags a inside your application received a directive attached to them.



.directive('a', function () {
    return {
         restrict: 'E',
         link: function (scope, elem, attrs) {
              // your code here
         }
    }
})

      

+3


source


Create an element directive that matches the elements <a>

and add a click handler there.

+1


source







All Articles