"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/ionic-ion-modal-lab/explore-ion-modal.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-ion-modal.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联37章) · 含当前章节或实例 · mbskycom202612a2013.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2028.zip