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

ionic 选项卡栏操作

系统梳理 Ionic 1 选项卡导航套件:`<ion-tabs>` 平台自适应停靠位置、`<ion-tab>` 全部 10 个属性与独立历史栈、`ng-click` 覆盖默认选中规则,以及 `$ionicTabsDelegate`(`select`/`selectedIndex`/`$getByHandle`),并对照现代 Ionic 7/8 `<ion-tabs>`。

学完这一章,你能够

  • 系统梳理 Ionic 1 选项卡导航套件:`<ion-tabs>` 平台自适应停靠位置、`<ion-tab>` 全部 10 个属性与独立历史栈、`ng-click` 覆盖默认选中规则,以及 `$ionicTabsDelegate`(`select`/`selectedIndex`/`$getByHandle`),并对照现代 Ionic 7/8 `<ion-tabs>`。

ion-tabs 容器、平台自适应停靠与基础示例

`<ion-tabs>` 将多个并行页面模块组织为多标签栏导航,用户点击标签即可在模块间切换。Ionic 1 默认遵循两大移动平台的交互规范:在 iOS 上选项卡栏停靠于屏幕底部,在 Android 上则默认出现在顶部导航栏下方(也可通过 `$ionicConfigProvider.tabs.position('bottom')` 统一)。示例在 `<ion-tabs class="tabs-positive tabs-icon-only">` 下声明了“首页”“关于”“设置”三个 `<ion-tab>`,分别为其配置选中态 `icon-on`(实心图标)与未选中态 `icon-off`(线框图标);容器级 API 为可选属性 `delegate-handle`,用于绑定 `$ionicTabsDelegate`。

ion-tab 独立历史栈与全量 10 个属性 API

`<ion-tab>` 必须隶属于 `<ion-tabs>`,其内部内容仅在对应标签被激活时呈现,并且每个 `<ion-tab>` 维护各自独立的导航历史栈(常嵌套独立命名的 `<ion-nav-view>`)。它支持 10 个核心属性:`title`(标签标题)、`href`(点击跳转链接)、`icon`(默认图标,同时作为 `icon-on` 与 `icon-off` 的回退默认值,注:源表误拼为 `ion-on`/`ion-off`)、`icon-on`(选中态图标)、`icon-off`(未选中态图标)、`badge`(角标徽章表达式,常为未读数字)、`badge-style`(徽章配色样式,注:源表误写作“微章”)、`on-select` 与 `on-deselect`(选中与取消选中回调)。特别需要注意 `ng-click` 的覆盖规则:一旦为 `<ion-tab>` 绑定了 `ng-click`,点击该标签将不再自动切换选中,开发者需在回调中按业务条件显式调用 `$ionicTabsDelegate.select(index)`。

$ionicTabsDelegate 编程控制与现代 Ionic 迁移

`$ionicTabsDelegate` 用于在控制器中编程切换或查询选项卡状态,直接调用会作用于所有 `<ion-tabs>`,通过 `$getByHandle(handle)` 则精确控制具名实例(例如 `$ionicTabsDelegate.$getByHandle('my-handle').select(0)`)。核心方法包含:`select(index, [shouldChangeHistory])`(按 0 起始下标选中标签;当选项卡内部嵌套 `<ion-nav-view>` 且希望恢复该标签原有浏览历史时,应将第二参 `shouldChangeHistory` 设为 `true`,默认 `false`)以及 `selectedIndex()`(返回当前选中标签下标,未选中任何标签时返回 `-1`)。迁移到现代 Ionic 7/8 时,选项卡结构升级为 `<ion-tabs>` + `<ion-tab-bar slot="bottom|top">` + `<ion-tab-button tab="...">` + `<ion-badge>`,并与框架路由器无缝衔接实现每栏独立历史栈。

ion-tabs 属性 API

属性类型详情
delegate-handle (可选)字符串标识当前选项卡栏实例的句柄,供 $ionicTabsDelegate.$getByHandle() 控制。

ion-tab 属性 API

属性类型详情
title字符串选项卡标题文案。
href (可选)字符串触碰该选项卡时跳转的目标路由链接。
icon (可选)字符串默认图标类名;给定后同时作为 icon-on 与 icon-off 的默认值(源表误拼为 ion-on/ion-off)。
icon-on (可选)字符串选项卡处于选中状态时显示的图标类名。
icon-off (可选)字符串选项卡处于未选中状态时显示的图标类名。
badge (可选)表达式显示在选项卡上的徽章值(通常为未读数量)。
badge-style (可选)表达式选项卡徽章样式类(如 badge-assertive / tabs-positive)。
on-select (可选)表达式该选项卡被选中时触发的表达式。
on-deselect (可选)表达式该选项卡从选中变为取消选中时触发的表达式。
ng-click (可选)表达式覆盖默认点击切换行为;设置后点击不会自动选中,需显式调用 $ionicTabsDelegate.select()。

$ionicTabsDelegate.select(index, [shouldChangeHistory]) 参数表

参数类型详情
index数值要选中的目标选项卡下标(从 0 开始)。
shouldChangeHistory (可选)布尔值是否加载该选项卡已有的浏览历史(默认 false);当标签内嵌 ion-nav-view 时通常设为 true。

$ionicTabsDelegate.$getByHandle(handle) 参数表

参数类型详情
handle字符串与 ion-tabs 上 delegate-handle 属性一致的句柄标识字符串。

运行 ion-tabs 指令解析、$ionicTabsDelegate 切换、ng-click 覆盖与平台位置对照离线实测

含完整源码 · 199 行
展开查看收起
python
"""Offline Ionic 1 ion-tabs, ion-tab & $ionicTabsDelegate verifier."""
import json
from lxml import html


class TabItem:
    def __init__(self, title, icon=None, icon_on=None, icon_off=None, href=None,
                 badge=None, badge_style=None, has_ng_click=False):
        self.title = title
        self.icon_on = icon_on or icon
        self.icon_off = icon_off or icon
        self.href = href
        self.badge = badge
        self.badge_style = badge_style
        self.has_ng_click = has_ng_click
        self.history_stack = [href or f"#/tab/{title}"]


class IonicTabsController:
    """Models ion-tabs container & $ionicTabsDelegate."""

    def __init__(self, handle, tabs):
        self.handle = handle
        self.tabs = list(tabs)
        self._selected = -1
        self.events = []

    def selected_index(self) -> int:
        return self._selected

    def select(self, index: int, should_change_history: bool = False):
        if not (0 <= index < len(self.tabs)):
            return -1
        if self._selected == index:
            return self._selected
        if self._selected >= 0:
            self.events.append(f"deselect:{self.tabs[self._selected].title}")
        self._selected = index
        tab = self.tabs[index]
        self.events.append(f"select:{tab.title}:hist={should_change_history}")
        return self._selected

    def click_tab(self, index: int):
        tab = self.tabs[index]
        if tab.has_ng_click:
            # Ionic 1 rule: when ng-click is set on ion-tab, auto-select is suppressed
            self.events.append(f"ng-click-intercept:{tab.title}")
            return self._selected
        return self.select(index, should_change_history=True)

    def active_icon(self, index: int):
        tab = self.tabs[index]
        return tab.icon_on if index == self._selected else tab.icon_off


class IonicTabsDelegate:
    def __init__(self, controllers):
        self._map = {c.handle: c for c in controllers}

    def get_by_handle(self, handle):
        return self._map[handle]


def main():
    cases = []

    # Case 1: Parse ion-tabs + ion-tab directives & attributes
    markup = """
    <ion-tabs delegate-handle="my-handle" class="tabs-positive tabs-icon-only">
      <ion-tab title="首页" icon-on="ion-ios-filing" icon-off="ion-ios-filing-outline"
               href="#/tab/home" badge="3" badge-style="badge-assertive"
               on-select="onTabSelected()" on-deselect="onTabDeselected()"></ion-tab>
      <ion-tab title="关于" icon="ion-ios-clock" href="#/tab/about"></ion-tab>
      <ion-tab title="设置" icon-on="ion-ios-gear" icon-off="ion-ios-gear-outline"
               ng-click="customSettingsAction()"></ion-tab>
    </ion-tabs>
    """
    doc = html.fromstring(markup)
    tabs_el = doc.xpath("//ion-tab")
    actual_dom = {
        "handle": doc.get("delegate-handle"),
        "classes": doc.get("class"),
        "tab_titles": [t.get("title") for t in tabs_el],
        "first_badge": tabs_el[0].get("badge"),
        "first_on_select": tabs_el[0].get("on-select"),
        "first_on_deselect": tabs_el[0].get("on-deselect"),
        "second_icon": tabs_el[1].get("icon"),
        "third_ng_click": tabs_el[2].get("ng-click"),
    }
    expected_dom = {
        "handle": "my-handle",
        "classes": "tabs-positive tabs-icon-only",
        "tab_titles": ["首页", "关于", "设置"],
        "first_badge": "3",
        "first_on_select": "onTabSelected()",
        "first_on_deselect": "onTabDeselected()",
        "second_icon": "ion-ios-clock",
        "third_ng_click": "customSettingsAction()",
    }
    cases.append({
        "name": "parse_ion_tabs_directives",
        "summary": "解析 ion-tabs 的 delegate-handle 与 ion-tab 全部核心属性",
        "expected": expected_dom,
        "actual": actual_dom,
        "passed": actual_dom == expected_dom,
    })

    # Case 2: $ionicTabsDelegate select / selectedIndex / $getByHandle & icon-on/off fallback
    ctrl = IonicTabsController("my-handle", [
        TabItem("首页", icon_on="ion-ios-filing", icon_off="ion-ios-filing-outline", href="#/tab/home"),
        TabItem("关于", icon="ion-ios-clock", href="#/tab/about"),
        TabItem("设置", icon_on="ion-ios-gear", icon_off="ion-ios-gear-outline", has_ng_click=True),
    ])
    delg = IonicTabsDelegate([ctrl])
    h = delg.get_by_handle("my-handle")
    initial_idx = h.selected_index()
    h.select(0, should_change_history=False)
    icons_at_0 = [h.active_icon(0), h.active_icon(1), h.active_icon(2)]
    h.select(1, should_change_history=True)
    icons_at_1 = [h.active_icon(0), h.active_icon(1), h.active_icon(2)]
    actual_del = {
        "initial_index": initial_idx,
        "selected_now": h.selected_index(),
        "icons_at_0": icons_at_0,
        "icons_at_1": icons_at_1,
        "events": list(h.events),
    }
    expected_del = {
        "initial_index": -1,
        "selected_now": 1,
        "icons_at_0": ["ion-ios-filing", "ion-ios-clock", "ion-ios-gear-outline"],
        "icons_at_1": ["ion-ios-filing-outline", "ion-ios-clock", "ion-ios-gear-outline"],
        "events": ["select:首页:hist=False", "deselect:首页", "select:关于:hist=True"],
    }
    cases.append({
        "name": "tabs_delegate_select_and_icons",
        "summary": "验证 $ionicTabsDelegate.select/selectedIndex、icon 默认回退与 on-select/on-deselect",
        "expected": expected_del,
        "actual": actual_del,
        "passed": actual_del == expected_del,
    })

    # Case 3: ng-click suppresses default tab selection until manual delegate.select()
    idx_after_ng_click = h.click_tab(2)
    idx_after_manual = h.select(2, should_change_history=False)
    actual_ng = {
        "after_ng_click_still_1": idx_after_ng_click,
        "after_manual_select_2": idx_after_manual,
        "last_events": h.events[-3:],
    }
    expected_ng = {
        "after_ng_click_still_1": 1,
        "after_manual_select_2": 2,
        "last_events": ["ng-click-intercept:设置", "deselect:关于", "select:设置:hist=False"],
    }
    cases.append({
        "name": "tab_ng_click_override_behavior",
        "summary": "验证设置 ng-click 后点击不自动切换,须显式调用 $ionicTabsDelegate.select()",
        "expected": expected_ng,
        "actual": actual_ng,
        "passed": actual_ng == expected_ng,
    })

    # Case 4: Platform default tab bar placement (iOS bottom vs Android top) & modern Ionic 7/8 <ion-tab-bar>
    placement = {"ios": "bottom", "android": "top"}
    modern = html.fromstring(
        '<ion-tabs><ion-tab-bar slot="bottom">'
        '<ion-tab-button tab="home"><ion-badge color="danger">3</ion-badge></ion-tab-button>'
        '</ion-tab-bar></ion-tabs>'
    )
    actual_modern = {
        "ionic1_default_placement": placement,
        "modern_slot": modern.xpath("//ion-tab-bar/@slot")[0],
        "modern_tab": modern.xpath("//ion-tab-button/@tab")[0],
        "modern_badge": modern.xpath("//ion-badge/text()")[0],
    }
    expected_modern = {
        "ionic1_default_placement": {"ios": "bottom", "android": "top"},
        "modern_slot": "bottom",
        "modern_tab": "home",
        "modern_badge": "3",
    }
    cases.append({
        "name": "platform_placement_and_modern_tabs",
        "summary": "核对 Ionic 1 iOS/Android 默认选项卡位置差异与现代 Ionic 7/8 ion-tab-bar/ion-badge",
        "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()
验证 ion-tabs/ion-tab 属性解析、select/selectedIndex 与 icon-on/off 回退、ng-click 拦截默认切换直至手动 select 以及 iOS/Android 位置与现代 ion-tab-bar 映射。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:Ionic

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

下载课程关联工程包:Ionic

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

Ionic 1 规定只要 ion-tab 设置了 ng-click 就会拦截默认的选中切换逻辑,把控制权完全交给开发者;登录成功后只需在控制器中调用 $ionicTabsDelegate.select(targetIndex) 即可完成切换。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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