Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing jQuery 'on' function in AngularJS

Tags:

angularjs

I have some legacy jQuery code that looks like the following:

$(document).on('replace', 'div', function (e, new_path, original_path) {
  // do stuff here
});

I'm trying to figure out how to move this code into an AngularJS consistent approach. The code above is running when index.html gets loaded. I'm trying to move initialization code into a directive. Currently, I'm calling the directive as shown here:

<body initialize-page>
  ... content goes here
</body>

My directive looks like the following:

.directive('initializePage', function ($document) {
    return {
        restrict: 'A',
        link: function (element) {
            console.log('initialization code goes here.');
        }
    };
})

However, I don't know what the AngularJS equivalent of 'on' is. I'd like to get away from using jQuery if at all possible.

Thanks!

like image 798
JQuery Mobile Avatar asked Dec 28 '13 20:12

JQuery Mobile


1 Answers

Angular includes a subset of jquery it calls jqLite. The jqlite version of .on has these constraints:

on() - Does not support namespaces, selectors or eventData

So, we can use the Angular on, but slightly differently than you did in jQuery (namely without the selector).

A directive's link function's second parameter is the element the directive is applied to. So, while we can't specify a selector in on, we can use find on the element parameter to get your div. Then we can chain the on to that result. This gives us the following link function:

link: function (scope,element,attrs) { 
         element.find('div').on('replace',  function (event) {
            console.log("got event: ",event);
         });
      };

Here's a demo fiddle in which I used click instead of replace just because it's easier to show.

like image 172
KayakDave Avatar answered Sep 28 '22 16:09

KayakDave