Friday, September 4, 2015

AngularJS and the case of "but I don't want to rewrite my event listeners." (also I have directives)

Well, damn. Shit son.....

Calling event listener functions outside of AngularJS is not that hard. There might be a "strong" discussion on how to do this but that's a matter of style. That is a whole other bowl of soup.

We can fix this in a jiffy and we just have to keep in mind that Angular elements are accessible via JQLite.

We start with our directive to which we will then attached a listener function.

// app.js
angular.module('myApp', [])
   .directive('myDirective', function myDirective () {
        return {
            restrict: 'AEC',
            link: myDirectiveLink

function myDirectiveLink (scope, element, attrs) {
    var someDOMElement = element[0];
    someDOMElement.addEventListener("click", myDirectiveEventListener, false);

function myDirectiveEventListener () {
    // Handle the event here
   // This could be an existing listener somewhere in a different source file

Now all we need is to declare 'myDirective' in a valid DOM element in our view. It will respond to a click event that will be handled by the 'myDirectiveEventListener' function.