蓝色天空网mbsky.com · 知识 · 实践 · 创造Ionic · 本地阅读预览
教程 / 移动开发 / Ionic

Ionic 上拉菜单(ActionSheet)

解析 Ionic 1 上拉菜单($ionicActionSheet)的交互规范、HTML 触发绑定、$ionicPlatform.ready 原生插件守卫、show() 配置项与回调返回值状态机,以及 hideSheet() 定时收起机制。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

上拉菜单交互规范与 HTML 触发结构

上拉菜单(ActionSheet)是从屏幕底部向上滑出的轻量级操作面板,用于在当前上下文中让用户快速选择后续动作。为了降低误触风险,具有破坏性的高危操作(如删除)会默认以醒目的红色高亮呈现;用户既可以点击底部的取消按钮,也可以轻触菜单外部空白遮罩区域将其关闭。HTML 视图中通过 `ng-app="starter"` 与 `ng-controller="actionsheetCtl"` 绑定应用与控制器,并在 `<ion-pane><ion-content>` 内以 `ng-click="show()"` 触发面板弹出。

$ionicActionSheet 服务配置、回调状态机与现代演进

在控制器中注入 `$ionicActionSheet` 与 `$timeout` 后,调用 `$ionicActionSheet.show(options)` 即可弹出菜单并获得一个用于手动关闭的 `hideSheet` 函数句柄。配置对象支持 `titleText`(顶部提示标题)、`buttons`(普通操作按钮数组,支持 HTML 文本如 `<b>Share</b> This` 与 `Move`)、`destructiveText`(红色危险操作文字如 `Delete`)、`cancelText`(底部取消按钮文字)以及对应回调:`buttonClicked(index)` 接收被点击普通按钮的索引,返回 `true` 时框架自动关闭菜单、返回 `false` 则保持打开;`destructiveButtonClicked()` 处理高危动作;`cancel()` 在点击取消或遮罩时触发。示例中还演示了通过 `$timeout(hideSheet, 2000)` 在 2 秒后以编程方式自动收起面板,并在模块 `.run($ionicPlatform)` 中安全检查 `window.cordova.plugins.Keyboard` 与 `window.StatusBar` 才调用原生插件。源页面的示例按钮与未缓存动图仅作静态登记;在现代 Ionic 7/8 中,对应 `<ion-action-sheet>` 或 `actionSheetController.create({ header, buttons: [{ text, role: 'destructive'|'cancel', handler }] })`。

运行 $ionicActionSheet 触发 DOM、按钮/高危/取消/遮罩回调状态机与平台守卫离线核验

python · 阅读源码
"""Offline Ionic 1 $ionicActionSheet DOM trigger & button/destructive/cancel/timeout state-machine verifier for Ch18 (actionsheet)."""
from __future__ import annotations

import json
from lxml import html

VERSION = "CPython 3.12.14 / lxml offline Ionic UI & component verifier"


def make_case(name: str, summary: str, expected, actual) -> dict:
    return {
        "name": name,
        "summary": summary,
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_actionsheet_trigger_dom() -> dict:
    markup = """
    <body ng-app="starter" ng-controller="actionsheetCtl">
      <ion-pane>
        <ion-content>
          <h2 ng-click="show()">Action Sheet</h2>
        </ion-content>
      </ion-pane>
    </body>
    """
    doc = html.document_fromstring(f"<html>{markup}</html>")
    body = doc.xpath("//body")[0]
    h2 = doc.xpath("//ion-pane/ion-content/h2")[0]
    actual = {
        "ng_app": body.get("ng-app"),
        "ng_controller": body.get("ng-controller"),
        "has_ion_pane": bool(doc.xpath("//ion-pane")),
        "trigger_ng_click": h2.get("ng-click"),
        "trigger_text": h2.text_content().strip(),
    }
    expected = {
        "ng_app": "starter",
        "ng_controller": "actionsheetCtl",
        "has_ion_pane": True,
        "trigger_ng_click": "show()",
        "trigger_text": "Action Sheet",
    }
    return make_case(
        "actionsheet_html_trigger_structure",
        "Parse ng-app, actionsheetCtl, <ion-pane>/<ion-content>, and ng-click='show()' trigger",
        expected,
        actual,
    )


def case_actionsheet_callback_state_machine() -> dict:
    class IonicActionSheetSimulator:
        def __init__(self) -> None:
            self.visible = False
            self.config: dict = {}
            self.events: list[str] = []

        def show(self, config: dict):
            self.config = config
            self.visible = True
            self.events.append(f"show:{config['titleText']}")
            return self.hide

        def hide(self) -> None:
            if self.visible:
                self.visible = False
                self.events.append("hide")

        def click_button(self, index: int) -> None:
            if not self.visible:
                return
            btn = self.config["buttons"][index]["text"]
            self.events.append(f"button:{index}:{btn}")
            cb = self.config.get("buttonClicked")
            if cb and cb(index) is True:
                self.hide()

        def click_destructive(self) -> None:
            if not self.visible:
                return
            self.events.append(f"destructive:{self.config['destructiveText']}")
            cb = self.config.get("destructiveButtonClicked")
            if cb is None or cb() is True:
                self.hide()

        def click_cancel_or_backdrop(self, source: str) -> None:
            if not self.visible:
                return
            self.events.append(f"dismiss:{source}")
            cb = self.config.get("cancel")
            if cb:
                cb()
            self.hide()

    sim = IonicActionSheetSimulator()
    cancel_calls = 0

    def on_cancel() -> None:
        nonlocal cancel_calls
        cancel_calls += 1

    cfg = {
        "buttons": [{"text": "<b>Share</b> This"}, {"text": "Move"}],
        "destructiveText": "Delete",
        "titleText": "Modify your album",
        "cancelText": "Cancel",
        "cancel": on_cancel,
        "buttonClicked": lambda idx: idx == 0,  # returns True for Share (closes), False for Move (stays open)
        "destructiveButtonClicked": lambda: True,
    }

    # Flow 1: Move returns False (stays open), then Share returns True (closes)
    hide_fn = sim.show(cfg)
    sim.click_button(1)
    open_after_move = sim.visible
    sim.click_button(0)
    open_after_share = sim.visible

    # Flow 2: Destructive button triggers red delete action and closes
    sim.show(cfg)
    sim.click_destructive()
    open_after_delete = sim.visible

    # Flow 3: Cancel / backdrop tap invokes cancel() and closes
    sim.show(cfg)
    sim.click_cancel_or_backdrop("backdrop")

    # Flow 4: $timeout(hideSheet, 2000) programmatic dismiss
    hide_fn = sim.show(cfg)
    open_before_timeout = sim.visible
    hide_fn()
    open_after_timeout = sim.visible

    actual = {
        "open_after_move_false": open_after_move,
        "open_after_share_true": open_after_share,
        "open_after_destructive": open_after_delete,
        "cancel_calls": cancel_calls,
        "open_before_timeout": open_before_timeout,
        "open_after_timeout": open_after_timeout,
        "event_count": len(sim.events),
    }
    expected = {
        "open_after_move_false": True,
        "open_after_share_true": False,
        "open_after_destructive": False,
        "cancel_calls": 1,
        "open_before_timeout": True,
        "open_after_timeout": False,
        "event_count": 12,
    }
    return make_case(
        "actionsheet_show_callbacks_and_timeout_hide",
        "Verify $ionicActionSheet.show() buttonClicked return semantics, destructive action, cancel/backdrop, and hideSheet() timeout",
        expected,
        actual,
    )


def case_platform_ready_and_modern_mapping() -> dict:
    # Verify Cordova Keyboard / StatusBar feature-detection guards in .run($ionicPlatform)
    def run_platform_ready(env: dict) -> list[str]:
        executed = []
        if env.get("cordova_keyboard"):
            executed.append("hideKeyboardAccessoryBar(true)")
        if env.get("status_bar"):
            executed.append("StatusBar.styleDefault()")
        return executed

    actual = {
        "browser_without_cordova": run_platform_ready({"cordova_keyboard": False, "status_bar": False}),
        "native_with_plugins": run_platform_ready({"cordova_keyboard": True, "status_bar": True}),
        "modern_component": "<ion-action-sheet> / actionSheetController.create({ header, buttons })",
    }
    expected = {
        "browser_without_cordova": [],
        "native_with_plugins": ["hideKeyboardAccessoryBar(true)", "StatusBar.styleDefault()"],
        "modern_component": "<ion-action-sheet> / actionSheetController.create({ header, buttons })",
    }
    return make_case(
        "actionsheet_platform_ready_guards_and_modern_api",
        "Verify $ionicPlatform.ready Cordova plugin guards and Ionic 7/8 <ion-action-sheet> migration",
        expected,
        actual,
    )


def main() -> None:
    cases = [
        case_actionsheet_trigger_dom(),
        case_actionsheet_callback_state_machine(),
        case_platform_ready_and_modern_mapping(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 验证 `actionsheetCtl`/`ng-click="show()"` DOM、`buttonClicked` 返回 `false` 保持打开与 `true` 关闭、危险删除动作、遮罩取消回调、`$timeout` 调用 `hideSheet()` 及 Cordova 插件空安全守卫。
运行 $ionicActionSheet 触发 DOM、按钮/高危/取消/遮罩回调状态机与平台守卫离线核验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:d6a64607c7d05f1528ab87db4f028391ff0ad22086bc3dc1f05614be0af3634f

下载本站示例源码

本地运行

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

下载Ionic 上拉菜单(ActionSheet)实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:a02f21acc6a1e3478d454bd307002df00596503d5fe7ea271381a4aaf997d008

常见错误与边界

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

练习与解答

在 `$ionicActionSheet.show()` 的 `buttonClicked(index)` 回调中,返回 `true` 和不返回/返回 `false` 有什么区别?返回值 `hideSheet` 有什么用途?

展开参考解答

`buttonClicked(index)` 返回 `true` 会通知 Ionic 在执行完业务逻辑后自动关闭上拉菜单,返回 `false` 或 `undefined` 则菜单保持展开;`$ionicActionSheet.show()` 返回的 `hideSheet` 是一个无参关闭函数,可用于在定时任务(`$timeout`)或外部事件到来时主动收起菜单。

规范与官方依据