我已经实现了模态指令,并将$modal.open
选项背景设置为false
。但是,现在我可以触发多个模态打开。有一种方法可以防止触发按钮在一个模态打开后触发吗?
var accountSummaryCtrl = function ($scope, $modal, $log) {
$scope.open = function () {
var modalInstance = $modal.open({
templateUrl: '/Apps/generic/modal/Templates/AccountSummary.html',
controller: ModalInstanceCtrl,
backdrop: false
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
};
由于
答案 0 :(得分:13)
使用布尔标志来避免它:
var accountSummaryCtrl = function ($scope, $modal, $log) {
var opened = false;
$scope.open = function () {
if (opened) return;
var modalInstance = $modal.open({
templateUrl: '/Apps/generic/modal/Templates/AccountSummary.html',
controller: ModalInstanceCtrl,
backdrop: false
});
opened = true;
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
opened = false;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
opened = false;
});
};
};
答案 1 :(得分:0)
我做了一个简单的指令,使用了与J. Bruni的答案相同的技术。
/**
* Directive which helps to prevent multiple modals opened when clicking same button many times.
*
* Just replace "ng-click" with "open-single-modal" in your html. Example:
*
* <button open-single-modal="openModal()">Open Window</button>
*
* NOTICE! "openModal()" function must return modalInstance which is a result of "$uibModal.open()"
*/
app.directive('openSingleModal', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var opened = false;
element.bind('click', function () {
if(opened) {
return;
}
opened = true;
var modalInstance = scope.$eval(attrs.openSingleModal);
if(!modalInstance || !modalInstance.result || typeof modalInstance.result.then !== 'function') {
console.error('Incorrect modal instance returned from the open modal function', element, modalInstance);
return;
}
modalInstance.result.then(function () {
opened = false;
}, function () {
opened = false;
});
});
}
};
});
要切换此指令的代码,只需将“ng-click”更改为“open-single-modal”,ng-click触发的函数必须返回模态实例。
实施例。之前:
<a ng-click="openModal()">Open Me!</a>
后:
<a open-single-modal="openModal()">Open Me!</a>
和
$scope.openModal = function() {
return $uibModal.open(...);
};
答案 2 :(得分:0)
J Bruni的答案非常好,但不要使用其他变量,而是使用modalInstance
已有的内容。由于您将模态实例声明为更高,因此您还可以灵活地在其他地方使用该变量(例如,当您可能想要关闭对话框时)。
link: function(scope, element, attrs) {
var modalInstance; /*assign to undefined if you like to be explicit*/
element.bind('click', function () {
if(modalInstance) {
return;
}
modalInstance = scope.$eval(attrs.openSingleModal);
if(!modalInstance || !modalInstance.result || typeof modalInstance.result.then !== 'function') {
console.error('Incorrect modal instance returned from the open modal function', element, modalInstance);
return;
}
modalInstance.result.then(function () {
modalInstance = undefined;
}, function () {
modalInstance = undefined;
});
});
}