Ionic 上拉菜单(ActionSheet)
解析 Ionic 1 上拉菜单($ionicActionSheet)的交互规范、HTML 触发绑定、$ionicPlatform.ready 原生插件守卫、show() 配置项与回调返回值状态机,以及 hideSheet() 定时收起机制。
学完这一章,你能够
- 解析 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、按钮/高危/取消/遮罩回调状态机与平台守卫离线核验
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`buttonClicked(index)` 返回 `true` 会通知 Ionic 在执行完业务逻辑后自动关闭上拉菜单,返回 `false` 或 `undefined` 则菜单保持展开;`$ionicActionSheet.show()` 返回的 `hideSheet` 是一个无参关闭函数,可用于在定时任务(`$timeout`)或外部事件到来时主动收起菜单。