Sweet-alert确认对话框的响应

时间:2015-10-29 12:27:39

标签: javascript angularjs confirm sweetalert

我有一个功能,我花了我的甜蜜警报对话框。我想在很多地方使用它,因此在一个函数中设置它:

$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;
            });

但我没有做出任何回应。实际上,我无法找到这样的例子,我认为这不是常用的使用方式。但是怎么可能呢?

2 个答案:

答案 0 :(得分:9)

根据用户是否按下确认按钮或取消按钮,您会想要不同的行为。

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回调中所做的任何更改都可以通过角度生命周期正确获取。如果您查看ng-sweet-alert的来源,您会看到作者将调用包裹在swal和用户的回调$rootScope.$evalAsync中,确保在调用和回调完成时进行角度更新

从代码风格的角度来看,最好将您的逻辑放入服务或工厂,以便在整个代码库中重用,而不是仅将其附加到$ rootScope。

答案 1 :(得分:0)

你不会得到回应,因为这是异步的, 您可以使用以下代码段

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
        }
      })