ionic2 AlertController,如何从方法返回按钮点击的值

时间:2017-04-02 06:28:04

标签: angular typescript ionic-framework ionic2

我在Typescript中相当新,我在提供程序中有以下代码

...
confirm(message, title=""){
        let confirm = this.alertCtrl.create({
            title: title || "Please confirm",
            message: message,
            buttons: [
                {
                  text: 'Yes',
                  handler: () => {
                    return true;
                  }
                },
                {
                  text: 'No',
                  handler: () => {
                    return false;
                  }
                }
              ]
        });

        confirm.present();
    }

更新

页面中有一个按钮,可以调用函数deleteItems

deleteItems(){
    this.popup.confirm("Are you sure you want to delete this item");
    if(this.popup.isTrue == true){
          //delete items
     }

}

我希望confirm方法返回true或false,具体取决于按钮"是"或"否"点击。

有谁能告诉我如何实现这个目标?

2 个答案:

答案 0 :(得分:2)

两个按钮各占一个处理程序。我会使用处理程序来设置a

定义箭头功能

a:boolean;
onYesHandler = ()=>{
   this.a = true;
}

onNoHandler = () =>{
   this.a = false;
}

confirm函数将处理程序与消息一起使用:

confirm(message, yesHandler,noHandler,title=""){
        let confirm = this.alertCtrl.create({
            title: title || "Please confirm",
            message: message,
            buttons: [
                {
                  text: 'Yes',
                  handler: yesHandler
                },
                {
                  text: 'No',
                  handler: noHandler
                }
              ]
        });

        confirm.present();
    }

调用confirm函数:

this.popup.confirm("Are you sure you want to delete this item",this.onYesHandler,this.onNoHandler);

答案 1 :(得分:2)

您可以按照以下所示进行操作。

注意:在Ionic2上将与Provider创建与UI相关的内容视为反模式因为provider将处理相关服务用例。记住这一点。

您想看看替代方案吗?请参阅2nd Method of my answer here.换句话说,您可以使用base class进行处理。

 isTrue:boolean=null;

    constructor(){}

    confirm(message, title=""){
            let confirm = this.alertCtrl.create({
                title: title || "Please confirm",
                message: message,
                buttons: [
                    {
                      text: 'Yes',
                       handler: data => {
                             this.isTrue=true;
                      }
                    },
                    {
                      text: 'No',
                     handler: data => {
                              this.isTrue=false;
                      }
                    }
                  ]
            });

            confirm.present();
        }