3

我有一个功能,可以定制我的甜蜜警报对话框。我想在很多地方使用它,因此将其设置为如下函数:

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

但我不接受任何回应。实际上,我找不到这样的例子,我认为它不是常用的使用方式。但怎么可能呢?

4

2 回答 2

11

听起来您想要根据用户是否按下确认按钮或取消按钮而采取不同的行为。

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。

于 2015-10-29T13:10:26.240 回答
1

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

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
        }
      })
    }
  }
);
于 2017-07-20T10:56:32.773 回答