ionic 模态窗口
深入讲解 Ionic 1 `$ionicModal` 服务(`fromTemplate`/`fromTemplateUrl`)与 `ionicModal` 实例完整生命周期(`initialize`、`show`、`hide`、`remove`、`isShown`、`modal.*` 事件及 `$destroy` 防泄漏清理),并对照现代 Ionic 7/8 `<ion-modal>`。
学完这一章,你能够
- 深入讲解 Ionic 1 `$ionicModal` 服务(`fromTemplate`/`fromTemplateUrl`)与 `ionicModal` 实例完整生命周期(`initialize`、`show`、`hide`、`remove`、`isShown`、`modal.*` 事件及 `$destroy` 防泄漏清理),并对照现代 Ionic 7/8 `<ion-modal>`。
$ionicModal 模板定义与实例化方法
`$ionicModal` 用于在主界面上方弹出覆盖式内容框(常见于新建表单、筛选面板与登录页)。模板可写入外部 HTML 文件,也可通过 `<script id="my-modal.html" type="text/ng-template">` 内联包裹 `<ion-modal-view>`;随后在控制器中注入 `$ionicModal`,通过 `fromTemplateUrl('my-modal.html', { scope: $scope, animation: 'slide-in-up' }).then(...)` 异步获取实例并挂载到作用域。
`$ionicModal` 提供两种构造入口:`fromTemplate(templateString, options)` 接收内联模板字符串并同步返回 `ionicModal` 实例;`fromTemplateUrl(templateUrl, options)` 接收模板地址或 `$templateCache` 键名,并返回一个符合 CommonJS Promise 规范的异步 Promise 对象,解析后交付 `ionicModal` 实例。两者都会把 `options` 透传给 `ionicModal#initialize`。
ionicModal 实例生命周期、防泄漏清理与选项
`ionicModal` 实例由 `$ionicModal` 创建。核心工程守则是:当所属作用域销毁(`$scope.$on('$destroy', ...)`)时,务必调用 `modal.remove()` 从 DOM 移除节点并回收事件监听,否则反复进出页面会造成内存泄漏。每次显示、隐藏或销毁时,模态框都会在其父作用域上广播 `'modal.shown'`、`'modal.hidden'` 与 `'modal.removed'` 事件并把自身作为参数传入。初始化 `options` 支持 `scope`(绑定作用域,默认创建 `$rootScope` 子作用域)、`animation`(入场/退场动画类名,默认 `'slide-in-up'`)、`focusFirstInput`(显示时是否自动聚焦首个输入框,默认 `false`)以及 `backdropClickToClose`(点击遮罩是否关闭,默认 `true`)。
实例操作方法统一采用 Promise 风格:`show()` 播放显示动画并返回动画完成后解析的 Promise;`hide()` 隐藏窗口并返回 Promise(节点仍保留在 DOM 以便复用);`remove()` 彻底移除 DOM 并释放资源;`isShown()` 同步返回布尔值以查询当前可见状态。
通讯录新建联系人实例与现代迁移
通讯录完整示例在主页展示 `contacts` 列表并在顶栏右侧放置撰写按钮触发 `modal.show()`;内联模板 `templates/modal.html` 内放置 `First Name`、`Last Name`、`Email` 输入框与 `Create` 按钮,提交时将拼接后的新联系人推入 `$scope.contacts` 并调用 `$scope.modal.hide()` 关闭弹窗。升级到现代 Ionic 7/8 时,`<ion-modal>` 与 `modalController.create()` 原生支持声明式 `trigger`、`is-open`、iOS 卡片堆叠(`presentingElement`)及底部抽屉式 Sheet Modal(`initialBreakpoint`/`breakpoints`)。
$ionicModal.fromTemplate(templateString, options) 参数表
| 参数 | 类型 | 详情 |
|---|---|---|
| templateString | 字符串 | 作为模态窗口内容的 HTML 模板字符串。 |
| options | 对象 | 透传给 ionicModal#initialize 的初始化选项对象。 |
$ionicModal.fromTemplateUrl(templateUrl, options) 参数表
| 参数 | 类型 | 详情 |
|---|---|---|
| templateUrl | 字符串 | 外部模板文件路径或 text/ng-template 脚本 id。 |
| options | 对象 | 透传给 ionicModal#initialize 的初始化选项对象。 |
ionicModal.initialize(options) 选项详情
| 参数 | 类型 | 详情 |
|---|---|---|
| options | 对象 | 可选字段:scope(父作用域,默认新建 $rootScope 子作用域)、animation(动画类,默认 'slide-in-up')、focusFirstInput(显示时是否聚焦首输入框,默认 false)、backdropClickToClose(点击背景是否关闭,默认 true)。 |
运行 $ionicModal 模板解析、fromTemplate/fromTemplateUrl、生命周期清理与联系人新增离线实测
"""Offline Ionic 1 $ionicModal & ionicModal lifecycle / template verifier."""
import json
from lxml import html
class IonicModalInstance:
"""Models Ionic 1 ionicModal controller instance lifecycle."""
def __init__(self, template_html, options=None):
opts = options or {}
self.template_html = template_html
self.scope_id = opts.get("scope", "$rootScope.$new()")
self.animation = opts.get("animation", "slide-in-up")
self.focus_first_input = bool(opts.get("focusFirstInput", False))
self.backdrop_click_to_close = bool(opts.get("backdropClickToClose", True))
self._shown = False
self._in_dom = True
self.events = []
def is_shown(self) -> bool:
return self._shown
def show(self) -> str:
assert self._in_dom, "Cannot show a removed modal"
self._shown = True
self.events.append("modal.shown")
return "resolved:shown"
def hide(self) -> str:
self._shown = False
self.events.append("modal.hidden")
return "resolved:hidden"
def remove(self) -> str:
self._shown = False
self._in_dom = False
self.events.append("modal.removed")
return "resolved:removed"
class IonicModalService:
"""Models $ionicModal.fromTemplate & fromTemplateUrl."""
def __init__(self, template_cache):
self.template_cache = dict(template_cache)
def from_template(self, template_string, options=None):
return IonicModalInstance(template_string, options)
def from_template_url(self, template_url, options=None):
tpl = self.template_cache[template_url]
# Returns a resolved promise-like tuple (status, instance)
return ("promise_resolved", IonicModalInstance(tpl, options))
def main():
cases = []
# Case 1: Parse <script type="text/ng-template"> containing <ion-modal-view>
tpl_markup = """
<div>
<script id="templates/modal.html" type="text/ng-template">
<ion-modal-view>
<ion-header-bar class="bar bar-header bar-positive">
<h1 class="title">New Contact</h1>
<button class="button button-clear button-primary" ng-click="modal.hide()">Cancel</button>
</ion-header-bar>
<ion-content class="padding">
<input ng-model="newUser.firstName" type="text">
<input ng-model="newUser.lastName" type="text">
<input ng-model="newUser.email" type="text">
<button class="button button-full button-positive" ng-click="createContact(newUser)">Create</button>
</ion-content>
</ion-modal-view>
</script>
</div>
"""
outer = html.fromstring(tpl_markup)
script_el = outer.xpath("//script[@type='text/ng-template']")[0]
inner = html.fromstring(script_el.text)
actual_dom = {
"template_id": script_el.get("id"),
"root_tag": inner.tag,
"modal_title": inner.xpath(".//h1[@class='title']/text()")[0],
"input_models": inner.xpath(".//input/@ng-model"),
"cancel_click": inner.xpath(".//ion-header-bar//button/@ng-click")[0],
"submit_click": inner.xpath(".//ion-content//button/@ng-click")[0],
}
expected_dom = {
"template_id": "templates/modal.html",
"root_tag": "ion-modal-view",
"modal_title": "New Contact",
"input_models": ["newUser.firstName", "newUser.lastName", "newUser.email"],
"cancel_click": "modal.hide()",
"submit_click": "createContact(newUser)",
}
cases.append({
"name": "parse_ng_template_modal_view",
"summary": "解析 text/ng-template 内嵌 ion-modal-view 与表单 ng-model 字段",
"expected": expected_dom,
"actual": actual_dom,
"passed": actual_dom == expected_dom,
})
# Case 2: fromTemplate (sync) vs fromTemplateUrl (Promise) & default initialize options
svc = IonicModalService({"templates/modal.html": script_el.text})
sync_modal = svc.from_template("<ion-modal-view>Inline</ion-modal-view>")
status, async_modal = svc.from_template_url("templates/modal.html", {
"scope": "AppCtrlScope",
"animation": "slide-in-up",
"focusFirstInput": True,
"backdropClickToClose": False,
})
actual_init = {
"sync_defaults": {
"scope": sync_modal.scope_id,
"animation": sync_modal.animation,
"focusFirstInput": sync_modal.focus_first_input,
"backdropClickToClose": sync_modal.backdrop_click_to_close,
},
"async_status": status,
"async_custom": {
"scope": async_modal.scope_id,
"animation": async_modal.animation,
"focusFirstInput": async_modal.focus_first_input,
"backdropClickToClose": async_modal.backdrop_click_to_close,
},
}
expected_init = {
"sync_defaults": {
"scope": "$rootScope.$new()",
"animation": "slide-in-up",
"focusFirstInput": False,
"backdropClickToClose": True,
},
"async_status": "promise_resolved",
"async_custom": {
"scope": "AppCtrlScope",
"animation": "slide-in-up",
"focusFirstInput": True,
"backdropClickToClose": False,
},
}
cases.append({
"name": "modal_from_template_and_options",
"summary": "验证 fromTemplate 与 fromTemplateUrl 及 initialize 默认与自定义选项",
"expected": expected_init,
"actual": actual_init,
"passed": actual_init == expected_init,
})
# Case 3: Full show -> isShown -> hide -> $destroy remove lifecycle & event broadcast
states = [async_modal.is_shown()]
r_show = async_modal.show()
states.append(async_modal.is_shown())
r_hide = async_modal.hide()
states.append(async_modal.is_shown())
r_remove = async_modal.remove()
states.append(async_modal.is_shown())
actual_life = {
"shown_states": states,
"results": [r_show, r_hide, r_remove],
"events": async_modal.events,
"in_dom_after_remove": async_modal._in_dom,
}
expected_life = {
"shown_states": [False, True, False, False],
"results": ["resolved:shown", "resolved:hidden", "resolved:removed"],
"events": ["modal.shown", "modal.hidden", "modal.removed"],
"in_dom_after_remove": False,
}
cases.append({
"name": "modal_lifecycle_and_cleanup",
"summary": "验证 show/hide/remove/isShown 状态流转及 modal.* 事件与 DOM 清理",
"expected": expected_life,
"actual": actual_life,
"passed": actual_life == expected_life,
})
# Case 4: Contacts creation workflow inside modal + hide
contacts = [
{"name": "Gordon Freeman"},
{"name": "Barney Calhoun"},
{"name": "Lamarr the Headcrab"},
]
m = svc.from_template_url("templates/modal.html", {"scope": "AppCtrl"})[1]
m.show()
new_user = {"firstName": "Alyx", "lastName": "Vance", "email": "alyx@example.org"}
contacts.append({"name": f"{new_user['firstName']} {new_user['lastName']}"})
m.hide()
actual_contacts = {
"count": len(contacts),
"last_name": contacts[-1]["name"],
"modal_closed": not m.is_shown(),
}
expected_contacts = {"count": 4, "last_name": "Alyx Vance", "modal_closed": True}
cases.append({
"name": "contacts_create_via_modal",
"summary": "验证通讯录实例通过模态表单新增联系人并关闭模态框",
"expected": expected_contacts,
"actual": actual_contacts,
"passed": actual_contacts == expected_contacts,
})
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()
- 验证 text/ng-template 内 ion-modal-view 解析、默认与自定义 initialize 选项、show/hide/remove/isShown 状态与事件序列以及联系人新增闭环。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:3222f7b9f97eac31862fc952f2545d8994294039a2013422c2437a11c94e22ec
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:ed6ba57991d1948ab0f7880598e43d88e02bbf677d276a6748385460cb7a6c89
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
ionicModal 的 hide() 和 remove() 有什么本质区别?何时应该调用 remove()?
展开参考解答
hide() 仅将模态框隐藏但保留 DOM 节点与作用域,适合用户可能多次打开的弹窗;remove() 会把节点从 DOM 彻底销毁并清理监听器,应在控制器 $scope.$on('$destroy') 时调用以避免内存泄漏。