我正在使用指令在单击它之外时关闭对话框。
我必须使用event.stopPropagation,以便打开按钮不会关闭它
它有效,但我觉得使用stopPropagation不是正确的方法,
有更好的方法吗?
或者使用stopPropagation可以吗?
我希望使用按钮或 programmaticaly 打开对话框。我希望它在外面点击时关闭。
以下是我的完整工作示例plunker
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', ['$scope', function($scope) {
$scope.dialogOpen = false;
$scope.closeDialog = function() {
console.log('closing');
$scope.dialogOpen = false;
};
$scope.openDialog = function($event) {
$event.stopPropagation();
console.log('opening');
$scope.dialogOpen = true;
};
}]);
myApp.directive('myDialog', ['$document', function($document) {
return {
restrict: 'A',
transclude: true,
scope: {
'close': '&'
},
template: "<div ng-transclude></div>",
link: function(scope, element) {
var handler = function(event) {
if (!element[0].contains(event.target)) {
console.log('click outside');
scope.$apply(scope.close());
}
};
console.log('creating handler');
$document.on('click', handler);
scope.$on('$destroy', function() {
$document.off('click', handler);
});
}
};
}]);