我使用Angular UI bootstrap模式,遇到了一些问题。
我想在bootstrap模态消除动画完成时调用一个函数。一旦模态开始被解除,下面的代码块将调用cancel()函数 - 而不是当模态消除动画完成时。
Angular UI不使用事件,因此没有' hidden.bs.modal'被解雇的事件(至少,据我所知)。
var instance = $modal.open({...});
instance.result.then(function(data) {
return success(data);
}, function() {
return cancel();
})
当模态开始关闭时,cancel()块立即运行。我需要在Bootstrap模式的关闭动画完成时执行代码。
如何通过角度UI实现这一目标?
参考组件:
https://angular-ui.github.io/bootstrap/#/modal
谢谢!
答案 0 :(得分:1)
有点晚了,但希望它仍然有帮助!您可以劫持uib-modal-window指令并检查其范围何时被销毁(它是一个独立的范围指令)。最终从文档中删除模态时,范围将被销毁。我还会使用服务来封装功能:
<强>服务强>
app.service('Modals', function ($uibModal, $q) {
var service = this,
// Unique class prefix
WINDOW_CLASS_PREFIX = 'modal-window-interceptor-',
// Map to save created modal instances (key is unique class)
openedWindows = {};
this.open = function (options) {
// create unique class
var windowClass = _.uniqueId(WINDOW_CLASS_PREFIX);
// check if we already have a defined class
if (options.windowClass) {
options.windowClass += ' ' + windowClass;
} else {
options.windowClass = windowClass;
}
// create new modal instance
var instance = $uibModal.open(options);
// attach a new promise which will be resolved when the modal is removed
var removedDeferred = $q.defer();
instance.removed = removedDeferred.promise;
// remember instance in internal map
openedWindows[windowClass] = {
instance: instance,
removedDeferred: removedDeferred
};
return instance;
};
this.afterRemove = function (modalElement) {
// get the unique window class assigned to the modal
var windowClass = _.find(_.keys(openedWindows), function (windowClass) {
return modalElement.hasClass(windowClass);
});
// check if we have found a valid class
if (!windowClass || !openedWindows[windowClass]) {
return;
}
// get the deferred object, resolve and clean up
var removedDeferred = openedWindows[windowClass].removedDeferred;
removedDeferred.resolve();
delete openedWindows[windowClass];
};
return this;
});
<强>指令强>
app.directive('uibModalWindow', function (Modals) {
return {
link: function (scope, element) {
scope.$on('$destroy', function () {
Modals.afterRemove(element);
});
}
}
});
并在控制器中使用它,如下所示:
app.controller('MainCtrl', function ($scope, Modals) {
$scope.openModal = function () {
var instance = Modals.open({
template: '<div class="modal-body">Close Me</div>' +
'<div class="modal-footer"><a class="btn btn-default" ng-click="$close()">Close</a></div>'
});
instance.result.finally(function () {
alert('result');
});
instance.removed.then(function () {
alert('closed');
});
};
});
我还写了一篇关于它的博客文章here。