我有一个名为 Progress
的服务,其方法名为 confirmation
,该方法采用 Progress.confirmation(message,accepted,rejected)
;
到目前为止的功能是:
if (!_.isString(message)) {
console.warn('No confirmation message was provided');
return false;
}
$rootScope.confirmation.message = message;
$('#confirmation').foundation('reveal', 'open');
// User confirms. If accepted() is provided, then run it
$rootScope.confirmationAccept = function() {
if (_.isFunction(accepted)) accepted();
$('#confirmation').foundation('reveal', 'close');
};
// User confirms. If rejected() is provided, then run it
$rootScope.confirmationReject = function() {
if (_.isFunction(rejected)) rejected();
$('#confirmation').foundation('reveal', 'close');
};
两个函数$rootScope.confirmationAccept()
和$rootScope.confirmationReject()
只是确认显示页面中的检查/取消按钮。
我想要做的是等待accepted()
/rejected()
执行,然后再关闭显示页面。我怎样才能做到这一点?
由于我传递了这两个函数,所以我不能真正相信编码人员会记住使用 $q
延迟,所以我认为这不是一个选择?另外,我不能依赖回调会返回值,因此我无法等待/观察返回值。
谢谢
最佳答案
不太清楚您的要求。
这确实应该是一个指令。上面的确认模式案例应该直接制定指令,这样您就不会受到魔法 dom 操纵或 rootscope 污染。
通常,您会将此逻辑封装在如下指令中:
<confirm-modal open="confirmationOpen" success="successCb()" abort="abortedCb" custom-message="'myCustomMessage'">
<button ng-click="launchConfirmation()">Click me or launch from controller</button>
这可以让您的 Controller 管理状态。
$scope.launchConfirmation() {
$scope.confirmationOpen = true;
}
$scope.successCb() {
//They Confirmed
//Do Async stuff
myAsync().then(function() {
$scope.confirmationOpen = false;
});
}
$scope.abortCb = function() {
//nothing async here
reset();
$scope.confirmationOpen = false;
};
关于Javascript/AngularJS - 等待回调完成执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24113265/