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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With