SweetAlert单击“取消”按钮后调用代码

时间:2017-07-06 15:16:51

标签: javascript angularjs sweetalert

我写了以下代码,我想在“取消”按钮下调用代码:

vm.saveGroup = function(){
    SweetAlert.swal({
        title: "Name this Device Group",
        text: "Please provide a name that you want your device group to be saved under. Also, make sure that you already specified all needed filters before you save the list.",
        type: "input",
        showCancelButton: true,
        closeOnConfirm: false,
        showLoaderOnConfirm: true,
        inputPlaceholder: "Device Group name"
    },
    function(inputValue){
        if (inputValue === false) {
            return false;
        }
        if (inputValue === "") {
            /*eslint-disable */
            swal.showInputError("You need to write something!");
            /*eslint-enable */
            return false;
        }

        deviceGroupsFactory.saveGroup(inputValue, vm.filterOutput)
            .then(function(response){
                if (response.status == 200){
                    SweetAlert.swal("Device Group saved!", "You should now see your device group on the list.", "success");
                    $state.go('main.template.devices.groups');
                }
                else {

                    SweetAlert.swal("Error!", response.statusText, "error");

                  console.log('xxx');
                }
            });
    });

}

但我不能称之为“取消点击”。我在文档中寻找但无法找到解决方案。

2 个答案:

答案 0 :(得分:6)

您向 swal 构造函数传递了太多参数。它只需要两个:

  

swal(选项,回调)

  • options:设计警报的属性
  • 回调:管理事件的回调函数

使用简单确认时,回调只会收到一个指示用户选择的参数:

  • true :确认
  • false :取消

使用inputbox,您将收到用户的输入字符串作为参数。

当您将输入框合并并确认时,您可以收到:

  • 输入字符串值:当用户按确认
  • false :当用户按取消时

所以,你必须使用Strict Equality Comparison 才能知道用户是否按下了取消或是否在输入框中插入了字符串false

请参阅以下简单示例:

swal({
  title: "Are you sure?",
  text: "Press CANCEL, please!",
  type: "input",
  showCancelButton: true,
  confirmButtonColor: "#DD6B55",
  confirmButtonText: "CONFIRM",
  cancelButtonText: "CANCEL",
  closeOnConfirm: false,
  closeOnCancel: false
},
function(inputValue){
  //Use the "Strict Equality Comparison" to accept the user's input "false" as string)
  if (inputValue===false) {
    swal("Well done!");
    console.log("Do here everything you want");
  } else {
    swal("Oh no...","press CANCEL please!");
    console.log("The user says: ", inputValue);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.min.js"></script>

我希望它可以帮助你,再见。

答案 1 :(得分:0)

您还可以使用.then

使用promise的实现

我给你举个例子,这将在按下按钮后立即执行

swal( 'Error!',valido.msj,'error').then((e)=>{
  if( valido.msj=="Enlace de botón No Válido" ){
     document.getElementById('link_btn_barra').focus();
  } 
});