[英]Response from Sweet-alert confirm dialog
我有一个功能,可以汇总我的甜蜜提示对话框。 我想在很多地方使用它,因此将其设置为如下功能:
$rootScope.giveConfirmDialog = function(title,text,confirmButtonText,toBeExecFunction){
swal({title: title,
text: title,
.....
confirmButtonText: confirmButtonText },
toBeExecFunction);
}
我想做的事情很简单:在某个地方调用该函数,然后根据用户的回答进行操作,因此:
var res = $scope.$root.giveConfirmDialog("..",
"test", "test", function () {
return true;
});
但是我没有任何回应。 实际上,我找不到这样的示例,我认为这不是常见的使用方式。 但是怎么可能呢?
听起来您想要基于用户是否按下确认按钮或取消按钮的不同行为。
SweetAlert通过回调函数上的参数公开用户响应。
这是SweetAlert Docs的直接示例:
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
swal("Deleted!", "Your imaginary file has been deleted.", "success");
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
}
);
在此示例中,当按下确认按钮时,将打开一个新的SweetAlert,以确认您的操作,如果按下了取消按钮,则将打开一个新的SweetAlert,并指出该操作已被取消。 您可以使用所需的任何功能替换这些呼叫。
由于该库使用异步回调,因此swal
方法没有返回值。
同样,使用ng-sweet-alert之类的库包装对Sweet Alert的调用可能是个好主意,以确保您在Sweet Alert回调中所做的任何更改都可以被角度生命周期正确地吸收。 如果您查看ng-sweet-alert的源代码,您会看到作者swal
的调用和用户的回调包装在$rootScope.$evalAsync
,确保在调用和回调完成时角度更新。
从代码样式的角度来看,最好将逻辑放入服务或工厂中以在整个代码库中重用,而不是仅将其附加到$ rootScope。
您将无法获得响应,因为它是异步的,您可以使用以下代码段:
swal({
title: "Are You Sure?",
text: "Are you sure to go ahead with this change?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
cancelButtonText: "No",
closeOnConfirm: true,
closeOnCancel: true,
},
function(isConfirm){
if (isConfirm) {
$.ajax({
url:"/path",
method:"GET",
data: {
category_id: category_id,
},
success:function(response) {
// tasks on reponse
}
})
}
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.