蓝色天空.知识 · 实践 · 创造
我的收藏
Ionic 教程目录 37章
Ionic / LEARN BY DOING

ionic 对话框

解析 Ionic 1 `$ionicPopup` 对话框服务的四种核心弹窗形态(`show()` 自定义校验弹窗、`confirm()` 确认框、`alert()` 警告框与 `prompt()` 输入框)、`onTap` 中 `e.preventDefault()` 拦截及 `.close()` 定时关闭,并对照 Ionic 7/8 `<ion-alert>`。

学完这一章,你能够

  • 解析 Ionic 1 `$ionicPopup` 对话框服务的四种核心弹窗形态(`show()` 自定义校验弹窗、`confirm()` 确认框、`alert()` 警告框与 `prompt()` 输入框)、`onTap` 中 `e.preventDefault()` 拦截及 `.close()` 定时关闭,并对照 Ionic 7/8 `<ion-alert>`。

$ionicPopup 四类弹窗方法与按钮模板

`$ionicPopup` 是 Ionic 1 提供的模态对话框服务,既支持高度定制的 `$ionicPopup.show(opts)`,也封装了三种高频便捷方法:`alert()`(单按钮提示警告框)、`confirm()`(返回布尔确认结果的双按钮确认框)与 `prompt()`(内置单行输入框的提示框)。示例页面通过三个按钮分别触发 `showPopup()`、`showConfirm()` 与 `showAlert()`,并预置了 `popup-template.html` 输入框模板片段。

自定义 onTap 校验拦截、超时关闭与现代迁移

在控制器 `PopupCtrl` 中,`$ionicPopup.show()` 演示了两个极具代表性的进阶技巧:第一,在 `Save` 按钮的 `onTap(e)` 回调中检查 `$scope.data.wifi` 是否为空,为空时调用 `e.preventDefault()` 阻止弹窗关闭,非空时返回密码值作为外层 `myPopup.then(res)` 的解析结果;第二,通过 `$timeout(() => myPopup.close(), 3000)` 实现 3 秒超时自动关闭。`confirm()` 的 Promise 在用户点击确认时解析为 `true`、取消时解析为 `false`;`alert()` 在确认后解析;`prompt()` 则在确认后解析为用户输入的字符串、取消时返回 `undefined`。迁移到现代 Ionic 7/8 时,警告、确认与带输入框对话框统一整合为 `<ion-alert>` 与 `alertController.create({ header, message, inputs, buttons })`。

运行 $ionicPopup.show() 校验拦截、confirm/alert/prompt 返回值与现代 ion-alert 离线实测

含完整源码 · 200 行
展开查看收起
python
"""Offline Ionic 1 $ionicPopup show/confirm/prompt/alert & onTap validation verifier."""
import json
from lxml import html


class TapEvent:
    def __init__(self):
        self.default_prevented = False

    def prevent_default(self):
        self.default_prevented = True


class IonicPopupInstance:
    def __init__(self, kind, config):
        self.kind = kind
        self.config = dict(config)
        self.closed = False
        self.result = None

    def tap_button(self, index):
        btn = self.config["buttons"][index]
        ev = TapEvent()
        on_tap = btn.get("onTap")
        val = on_tap(ev) if on_tap else btn.get("default_return")
        if ev.default_prevented:
            return {"closed": False, "prevented": True, "result": None}
        self.closed = True
        self.result = val
        return {"closed": True, "prevented": False, "result": val}

    def close(self, result=None):
        self.closed = True
        self.result = result


class IonicPopupService:
    def show(self, config):
        return IonicPopupInstance("show", config)

    def confirm(self, config):
        cfg = dict(config)
        cfg["buttons"] = [
            {"text": "Cancel", "default_return": False},
            {"text": "OK", "default_return": True},
        ]
        return IonicPopupInstance("confirm", cfg)

    def alert(self, config):
        cfg = dict(config)
        cfg["buttons"] = [{"text": "OK", "default_return": True}]
        return IonicPopupInstance("alert", cfg)

    def prompt(self, config, input_value=""):
        cfg = dict(config)
        cfg["buttons"] = [
            {"text": "Cancel", "default_return": None},
            {"text": "OK", "onTap": lambda e: input_value},
        ]
        return IonicPopupInstance("prompt", cfg)


def main():
    cases = []

    # Case 1: Parse HTML popup trigger buttons & ng-template password input
    markup = """
    <body class="padding" ng-controller="PopupCtrl">
      <button class="button button-dark" ng-click="showPopup()">弹窗显示</button>
      <button class="button button-primary" ng-click="showConfirm()">确认对话框</button>
      <button class="button button-positive" ng-click="showAlert()">警告框</button>
      <script id="popup-template.html" type="text/ng-template">
        <input ng-model="data.wifi" type="text" placeholder="Password">
      </script>
    </body>
    """
    doc = html.fromstring(markup)
    clicks = doc.xpath("//button/@ng-click")
    tpl = html.fromstring(doc.xpath("//script[@id='popup-template.html']")[0].text)
    actual_dom = {
        "button_handlers": clicks,
        "template_input_model": tpl.get("ng-model"),
        "template_placeholder": tpl.get("placeholder"),
    }
    expected_dom = {
        "button_handlers": ["showPopup()", "showConfirm()", "showAlert()"],
        "template_input_model": "data.wifi",
        "template_placeholder": "Password",
    }
    cases.append({
        "name": "parse_popup_triggers_and_template",
        "summary": "解析三个弹窗按钮的 ng-click 绑定及 popup-template.html 输入模板",
        "expected": expected_dom,
        "actual": actual_dom,
        "passed": actual_dom == expected_dom,
    })

    # Case 2: $ionicPopup.show() onTap e.preventDefault() validation & .close() timeout
    svc = IonicPopupService()
    scope_data = {"wifi": ""}

    def on_save(e):
        if not scope_data["wifi"]:
            e.prevent_default()
            return None
        return scope_data["wifi"]

    popup = svc.show({
        "title": "Enter Wi-Fi Password",
        "subTitle": "Please use normal things",
        "template": '<input type="password" ng-model="data.wifi">',
        "buttons": [
            {"text": "Cancel", "default_return": None},
            {"text": "<b>Save</b>", "type": "button-positive", "onTap": on_save},
        ],
    })
    empty_attempt = popup.tap_button(1)
    scope_data["wifi"] = "S3cret-WiFi"
    valid_attempt = popup.tap_button(1)

    # Timeout auto-close path
    popup2 = svc.show({"title": "Auto close", "buttons": [{"text": "Cancel"}]})
    popup2.close()
    actual_show = {
        "empty_attempt": empty_attempt,
        "valid_attempt": valid_attempt,
        "timeout_closed": popup2.closed,
    }
    expected_show = {
        "empty_attempt": {"closed": False, "prevented": True, "result": None},
        "valid_attempt": {"closed": True, "prevented": False, "result": "S3cret-WiFi"},
        "timeout_closed": True,
    }
    cases.append({
        "name": "popup_show_ontap_validation",
        "summary": "验证 $ionicPopup.show() 空密码 e.preventDefault() 拦截、有效提交返回与 close()",
        "expected": expected_show,
        "actual": actual_show,
        "passed": actual_show == expected_show,
    })

    # Case 3: confirm(), alert() & prompt() built-in dialogs
    c_ok = svc.confirm({"title": "Consume Ice Cream", "template": "Are you sure?"}).tap_button(1)
    c_cancel = svc.confirm({"title": "Consume Ice Cream", "template": "Are you sure?"}).tap_button(0)
    a_ok = svc.alert({"title": "Don't eat that!", "template": "It might taste good"}).tap_button(0)
    p_ok = svc.prompt({"title": "Wi-Fi", "template": "Enter password"}, input_value="guest123").tap_button(1)
    p_cancel = svc.prompt({"title": "Wi-Fi", "template": "Enter password"}, input_value="guest123").tap_button(0)
    actual_builtin = {
        "confirm_ok": c_ok["result"],
        "confirm_cancel": c_cancel["result"],
        "alert_ok": a_ok["result"],
        "prompt_ok": p_ok["result"],
        "prompt_cancel": p_cancel["result"],
    }
    expected_builtin = {
        "confirm_ok": True,
        "confirm_cancel": False,
        "alert_ok": True,
        "prompt_ok": "guest123",
        "prompt_cancel": None,
    }
    cases.append({
        "name": "popup_confirm_alert_prompt",
        "summary": "验证 $ionicPopup 的 confirm()、alert() 与 prompt() 按钮返回值语义",
        "expected": expected_builtin,
        "actual": actual_builtin,
        "passed": actual_builtin == expected_builtin,
    })

    # Case 4: Modern Ionic 7/8 <ion-alert> unification check
    modern = html.fromstring('<ion-alert trigger="open-alert" header="Confirm" message="Proceed?"></ion-alert>')
    actual_modern = {
        "tag": modern.tag,
        "trigger": modern.get("trigger"),
        "header": modern.get("header"),
        "message": modern.get("message"),
    }
    expected_modern = {
        "tag": "ion-alert",
        "trigger": "open-alert",
        "header": "Confirm",
        "message": "Proceed?",
    }
    cases.append({
        "name": "modern_ion_alert_wc",
        "summary": "核对现代 Ionic 7/8 <ion-alert> 统一替代 alert/confirm/prompt 属性",
        "expected": expected_modern,
        "actual": actual_modern,
        "passed": actual_modern == expected_modern,
    })

    print(json.dumps({
        "version": "CPython 3.12.14 / lxml offline Ionic JS directive & service verifier",
        "cases": cases,
    }, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
验证三按钮与模板解析、空密码 e.preventDefault() 阻止关闭及有效提交返回值、confirm/alert/prompt 结果语义及现代 <ion-alert> 写法。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a2013.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Ionic

课程关联工程包(登记关联37章) · 含当前章节或实例 · mbskycom202612a2013.zip

下载课程关联工程包:Ionic

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2041.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

在 onTap(e) 内判断绑定模型为空时调用 e.preventDefault() 即可阻止默认关闭行为;校验通过后返回需要传给 popup.then(res) 的数据值。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习