来自 Sweet-alert 确认对话框的响应

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 方法中没有 return 值。

此外,使用 ng-sweet-alert 之类的库来包装对 sweet alert 的调用可能是个好主意,以确保您在 Sweet Alert 回调中所做的任何更改都能被 angular 生命周期。如果您查看 ng-sweet-alert 的源代码,您会看到作者包装了对 swal 的调用和 $rootScope.$evalAsync 中的用户回调,确保 angular 在调用和回调完成。

从代码风格的角度来看,最好将您的逻辑放入服务或工厂中以便在整个代码库中重用,而不是将其附加到 $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
        }
      })
    }
  }
);