I have an element that I use $swipe.bind (from ngTouch) on to connect some event handlers inside a controller constructor:
$swipe.bind($(element_selector), {'move': dragMoveHandler});
I moved that element into an ngInclude, but now the controller constructor runs before the ngInclude is processed by Angular, so the $swipe.bind
call fails as $(element_selector)
is undefined
when it executes.
I looked into using $includeContentLoaded
to detect when the ngInclude has been processed, but it isn't clear which ngInclude has been loaded each time it fires, so my code would need to count the number of includes that have loaded before knowing that it's safe to use $swipe.bind
, which doesn't seem like a robust solution.
How can I do this?
Why don't you simply check if the element exist when the $includeContentLoaded is triggered
$rootScope.$on('$includeContentLoaded', function(event) {
if($(element_selector).length){
$swipe.bind($(element_selector), {'move': dragMoveHandler});
}
});
or if you want to avoid injecting the $rootScope and using angular events, why don't you simply do this in a simple vanilla JavaScript way
setTimeout(function check_if_element_exist(){
if($(element_selector).length){
$swipe.bind($(element_selector), {'move': dragMoveHandler});
}
else {
setTimeout(check_if_element_exist, 0);
}
}, 0);
You can even move this logic to a decorative directive so that you don't violate the SoC principle.