Here is my link function for my directive
function linkFunc(scope, element, attr){
// Detect Element Click Logic
scope.myCtrl.clickedElsewhere = {value: true};
$document.on('click', function(){
scope.myCtrl.clickedElsewhere.value = true;
scope.$apply();
});
element.on('click', function(){
event.stopPropagation();
scope.myCtrl.clickedElsewhere.value = false;
scope.$apply();
});
// End Detect Element Click Logic
}
As we can see, we used $document.on() and scope.apply , this means that for every click on anywhere in the document we will trigger a digest cycle. If we have alot of $watch triggers this might cause the web page to slow down. Although this implementation is not every efficient, I can't think of other ways to detect on element click and off element click for expanding and contracting my element.
Can someone provide some insight?
Thanks
it would be a lot more efficient to check scope.myCtrl.clickedElsewhere.value before calling $apply() in the document click handler:
$document.on('click', function(){
if(!scope.myCtrl.clickedElsewhere.value){
scope.myCtrl.clickedElsewhere.value = true;
scope.$apply();
}
});
This will prevent needless digests when there is no change in it's status.
You could also remove this click listener and reapply it when you click on element:
function docHandler() {
if (!scope.myCtrl.clickedElsewhere.value) {
scope.myCtrl.clickedElsewhere.value = true;
scope.$apply();
$document.off('click');//remove event listener completely
}
}
element.on('click', function() {
event.stopPropagation();
scope.myCtrl.clickedElsewhere.value = false;
scope.$apply();
$document.on('click', docHandler);// add document listener
});
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