[英]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.