Malk Malk - 1 month ago 5
AngularJS Question

Angular directive, trigger scope function

I have a custom popup panel that I want to add functionality to close whenever the screen is clicked outside the panel. I created a directive to accomplish this, but I am having a hard time communicating that the close event happened.

<div ng-if="ui.showConfig" auto-hide="ui.showConfig=false">...</div>


JS

myApp.directive('autoHide',
[function() {
return {
restrict: 'A',
scope: {
'autoHide': '&'
},
link: function (scope, element, attrs) {
var $overlay = $("<div style='position:absolute;top:0;left:0;width:100%;height:100%;z-index:2000;'>");
$overlay
.appendTo("body")
.one("click", function(e){
element.hide();
$overlay.unbind().remove();
// This is not firing...
// scope.autoHide();
});

element.css("zIndex", "2001");

element.on('$destroy', function() {
$overlay.unbind().remove();
});
}
};
}]);


Here is a jsfiddle

The overlay click event is firing. The panel is hiding. But
ui.showConfig
is not getting set to false causing the user to click the button twice to open up the panel next time.

Also, if there is another approach I should consider please let me know!

Answer

Inside an event handler you need to call scope.$apply() so that angular gets informed about changes:

// This is not firing...
scope.autoHide(); 
scope.$apply();