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

AngularJS 路由

核对 ngRoute 单页应用哈希路由原理、1.6 前后前缀差异、$routeProvider.when/otherwise 配置对象属性,以及内嵌与远程模板的 Chromium 实测。

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

学完这一章,你能够

单页应用(SPA)与哈希路由机制

AngularJS 路由机制允许前端依据不同的 URL 片段展示对应的视图与控制器,从而构建多视图单页 Web 应用(SPA,Single Page Application)。与传统多页路径(如 `https://example.com/first/page`)不同,AngularJS 1.6 及以上版本默认采用 `#!`(Hashbang)前缀来标识客户端路由(例如 `#!/first`、`#!/second`、`#!/third`),而在 AngularJS 1.6 之前默认仅使用 `#` 前缀(如 `#/first`)。

浏览器在发起 HTTP 请求时不会将 `#` 或 `#!` 之后的片段发送给服务器,因此点击不同哈希链接时服务端始终只接收同一主文档路径,前端路由模块则负责监听哈希变更,把不同逻辑路径映射到对应的视图(Views)与控制器(Controllers),例如将 `/ShowOrders` 与 `/AddNewOrder` 分别绑定到各自的模板与逻辑处理函数。本站实测确认:在 `#/computers` 与 `#!/printers` 之间切换时,`location.pathname` 始终维持 `'/'` 不变。

ngRoute 基础接入四步流程与实测

在 AngularJS 中启用基础路由需完成四项配置:第一步引入独立的 `angular-route.js`(或压缩版 `angular-route.min.js`);第二步在主模块声明依赖 `angular.module('routingDemoApp', ['ngRoute'])`;第三步在页面放置视图占位容器 `<div ng-view></div>`,该容器内的 DOM 会随当前命中路由自动替换。

第四步通过模块的 `.config(['$routeProvider', function($routeProvider) { ... }])` 注入 `$routeProvider`,按顺序调用 `when(path, routeConfig)` 注册路由规则,并用 `otherwise(routeConfig)` 指定未匹配时的兜底重定向。其中 `when` 的第一个参数为 URL 路径或匹配规则,第二个参数为路由配置对象。本站在本地环回服务与 Chromium 中依次点击 `#!/`、`#!/computers`、`#!/printers` 及未注册路径 `#!/blabla`,`ng-view` 依次渲染“这是首页页面”“这是电脑分类页面”“这是打印机页面”,未知路径自动重定向回 `#!/` 并显示首页内容,全程服务端根文档 `/` 请求次数始终保持 `1` 次(零整页刷新)。

路由配置对象参数与内嵌/远程模板实战

`$routeProvider.when(url, config)` 的配置对象支持六项常用属性:`template` 用于直接传入简短 HTML 字符串(如 `.when('/computers', {template: '这是电脑分类页面'})`);`templateUrl` 用于指定外部 HTML 模板文件路径(如 `views/computers.html`)或页面内嵌模板 ID,路由激活时将拉取内容注入 `ng-view`。本站实测访问指向 `/views/computers.html` 的路由时,浏览器按需向环回服务发出 `1` 次模板请求并渲染“外部模板:电脑分类”。

其余四项配置用于控制逻辑与跳转:`controller`(字符串、函数或数组标注)指定在该模板新作用域上执行的控制器;`controllerAs` 为控制器实例指定视图别名;`redirectTo` 定义重定向目标路径或计算函数;`resolve` 以键值映射声明控制器实例化前须预先解析的依赖项或异步数据。配合 `<script type="text/ng-template" id="embedded.home.html">` 内嵌模板可免去额外网络请求:本站实测切换 `#!/tpl-home` 与 `#!/tpl-about` 时,分别加载内嵌模板渲染 `Home` / `About` 标题,并正确注入 `HomeController`、`AboutController` 与 `resolve` 返回值(`ready-home` / `ready-about`)。

离线 Chromium 环回服务实测 Hashbang 路由切换、内嵌模板与远程 templateUrl

python · 阅读源码
"""Offline Playwright Chromium lab for AngularJS Ch 24: routing (ngRoute, $routeProvider, ng-view, ng-template)."""
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from playwright.sync_api import sync_playwright

ROUTE_HTML = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>AngularJS 路由离线实验</title></head>
<body>
  <script type="text/ng-template" id="embedded.home.html"><h1>Home</h1><p class="ctrl-info"></p></script>
  <script type="text/ng-template" id="embedded.about.html"><h1>About</h1><p class="ctrl-info"></p></script>

  <nav id="nav-basic">
    <a id="lnk-home" href="#!/">首页</a>
    <a id="lnk-computers" href="#!/computers">电脑</a>
    <a id="lnk-printers" href="#!/printers">打印机</a>
    <a id="lnk-unknown" href="#!/blabla">其他</a>
    <a id="lnk-tpl-home" href="#!/tpl-home">内嵌Home</a>
    <a id="lnk-tpl-about" href="#!/tpl-about">内嵌About</a>
    <a id="lnk-remote" href="#!/remote-computers">远程模板</a>
  </nav>
  <div id="view" ng-view></div>

  <script>
    // Self-contained offline ngRoute ($routeProvider + ng-view + $templateCache) equivalence runtime
    function createRouteEngine(hashPrefix) {
      const routes = [];
      let fallback = null;
      const controllers = {};
      const templateCache = new Map();
      document.querySelectorAll('script[type="text/ng-template"]').forEach((s) => {
        templateCache.set(s.id, s.textContent.trim());
      });

      const $routeProvider = {
        when(path, cfg) {
          routes.push({ path, cfg });
          return $routeProvider;
        },
        otherwise(cfg) {
          fallback = cfg;
          return $routeProvider;
        }
      };

      const $route = { current: null };

      function currentPath() {
        const raw = window.location.hash || '';
        const prefix = '#' + hashPrefix;
        if (raw.startsWith(prefix)) return raw.slice(prefix.length) || '/';
        if (raw.startsWith('#/')) return raw.slice(1);
        return '/';
      }

      async function renderRoute() {
        const path = currentPath();
        const hit = routes.find((r) => r.path === path);
        if (!hit) {
          if (fallback && fallback.redirectTo) {
            window.location.hash = '#' + hashPrefix + fallback.redirectTo;
            return renderRoute();
          }
          return null;
        }
        const cfg = hit.cfg;
        if (cfg.redirectTo) {
          window.location.hash = '#' + hashPrefix + cfg.redirectTo;
          return renderRoute();
        }
        const resolved = {};
        if (cfg.resolve) {
          for (const [k, fn] of Object.entries(cfg.resolve)) {
            resolved[k] = await fn();
          }
        }
        let html = '';
        if (typeof cfg.template === 'string') {
          html = cfg.template;
        } else if (cfg.templateUrl) {
          if (templateCache.has(cfg.templateUrl)) {
            html = templateCache.get(cfg.templateUrl);
          } else {
            const resp = await fetch(cfg.templateUrl);
            html = await resp.text();
          }
        }
        $route.current = { originalPath: hit.path, controller: cfg.controller || null, controllerAs: cfg.controllerAs || null, resolved };
        const view = document.querySelector('[ng-view]');
        view.innerHTML = html;
        if (cfg.controller && controllers[cfg.controller]) {
          const scope = {};
          const ctrlInst = {};
          controllers[cfg.controller].call(ctrlInst, scope, $route, resolved);
          if (cfg.controllerAs) scope[cfg.controllerAs] = ctrlInst;
          const infoEl = view.querySelector('.ctrl-info');
          if (infoEl) {
            infoEl.textContent = (scope.label || ctrlInst.label || '') + (resolved.tag ? ':' + resolved.tag : '');
          }
        }
        return $route.current;
      }

      return {
        $routeProvider,
        $route,
        controller(name, fn) { controllers[name] = fn; },
        renderRoute,
        currentPath
      };
    }

    const engine = createRouteEngine('!');
    engine.controller('HomeController', function($scope, $route, resolved) {
      $scope.label = 'HomeController';
      this.label = 'homeVm';
      $scope.$route = $route;
    });
    engine.controller('AboutController', function($scope, $route, resolved) {
      $scope.label = 'AboutController';
      this.label = 'aboutVm';
      $scope.$route = $route;
    });
    engine.$routeProvider
      .when('/', { template: '这是首页页面' })
      .when('/computers', { template: '这是电脑分类页面' })
      .when('/printers', { template: '这是打印机页面' })
      .when('/tpl-home', {
        templateUrl: 'embedded.home.html',
        controller: 'HomeController',
        controllerAs: 'vm',
        resolve: { tag: () => Promise.resolve('ready-home') }
      })
      .when('/tpl-about', {
        templateUrl: 'embedded.about.html',
        controller: 'AboutController',
        controllerAs: 'vm',
        resolve: { tag: () => Promise.resolve('ready-about') }
      })
      .when('/remote-computers', {
        templateUrl: '/views/computers.html'
      })
      .otherwise({ redirectTo: '/' });

    window.__routeEngine = engine;
    window.addEventListener('hashchange', () => { engine.renderRoute(); });
    engine.renderRoute();
  </script>
</body>
</html>
"""


class _RouteHandler(BaseHTTPRequestHandler):
    hits = []

    def log_message(self, format, *args):
        return

    def _send(self, body: str):
        data = body.encode("utf-8")
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        _RouteHandler.hits.append(self.path)
        if self.path == "/":
            self._send(ROUTE_HTML)
        elif self.path == "/views/computers.html":
            self._send('<section id="remote-tpl"><h3>外部模板:电脑分类</h3></section>')
        else:
            self.send_error(404)


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    _RouteHandler.hits = []
    srv = ThreadingHTTPServer(("127.0.0.1", 0), _RouteHandler)
    port = srv.server_address[1]
    t = threading.Thread(target=srv.serve_forever, daemon=True)
    t.start()

    cases = []
    try:
        with sync_playwright() as p:
            browser = launch_browser(p)
            try:
                page = browser.new_page()
                page.goto(f"http://127.0.0.1:{port}/", wait_until="load")

                # Case 1: Basic #!/ route switching & .otherwise redirect with zero extra '/' HTTP requests
                page.click("#lnk-home")
                v_home = page.locator("#view").inner_text()
                page.click("#lnk-computers")
                v_comp = page.locator("#view").inner_text()
                page.click("#lnk-printers")
                v_print = page.locator("#view").inner_text()
                page.click("#lnk-unknown")
                page.wait_for_function("() => window.location.hash === '#!/'")
                v_fallback = page.locator("#view").inner_text()
                hash_after_fallback = page.evaluate("() => window.location.hash")
                root_requests = sum(1 for h in _RouteHandler.hits if h == "/")
                res1 = {
                    "home": v_home,
                    "computers": v_comp,
                    "printers": v_print,
                    "fallback_view": v_fallback,
                    "fallback_hash": hash_after_fallback,
                    "server_root_hits": root_requests,
                }
                exp1 = {
                    "home": "这是首页页面",
                    "computers": "这是电脑分类页面",
                    "printers": "这是打印机页面",
                    "fallback_view": "这是首页页面",
                    "fallback_hash": "#!/",
                    "server_root_hits": 1,
                }
                cases.append(dict(
                    name="hashbang_route_switching_and_otherwise",
                    expected=exp1,
                    actual=res1,
                    passed=(res1 == exp1),
                ))

                # Case 2: Pre-1.6 '#' vs 1.6+ '#!' prefix resolution & unchanged pathname
                res2 = page.evaluate("""() => {
                    window.location.hash = '#/computers';
                    const pre16Path = window.__routeEngine.currentPath();
                    const pathname1 = window.location.pathname;
                    window.location.hash = '#!/printers';
                    const v16Path = window.__routeEngine.currentPath();
                    const pathname2 = window.location.pathname;
                    return {
                        pre16_parsed_path: pre16Path,
                        v16_parsed_path: v16Path,
                        pathname_unchanged: pathname1 === '/' && pathname2 === '/'
                    };
                }""")
                exp2 = {
                    "pre16_parsed_path": "/computers",
                    "v16_parsed_path": "/printers",
                    "pathname_unchanged": True,
                }
                cases.append(dict(
                    name="pre16_hash_prefix_vs_16_hashbang",
                    expected=exp2,
                    actual=res2,
                    passed=(res2 == exp2),
                ))

                # Case 3: Embedded script[type="text/ng-template"] + controller + controllerAs + resolve
                page.click("#lnk-tpl-home")
                page.wait_for_selector("#view h1")
                home_h1 = page.locator("#view h1").inner_text()
                home_info = page.locator("#view .ctrl-info").inner_text()
                page.click("#lnk-tpl-about")
                page.wait_for_function("() => document.querySelector('#view h1')?.textContent === 'About'")
                about_h1 = page.locator("#view h1").inner_text()
                about_info = page.locator("#view .ctrl-info").inner_text()
                res3 = {
                    "home_h1": home_h1,
                    "home_ctrl_resolve": home_info,
                    "about_h1": about_h1,
                    "about_ctrl_resolve": about_info,
                }
                exp3 = {
                    "home_h1": "Home",
                    "home_ctrl_resolve": "HomeController:ready-home",
                    "about_h1": "About",
                    "about_ctrl_resolve": "AboutController:ready-about",
                }
                cases.append(dict(
                    name="embedded_ng_template_and_controller",
                    expected=exp3,
                    actual=res3,
                    passed=(res3 == exp3),
                ))

                # Case 4: Remote templateUrl fetched over HTTP into ng-view
                page.click("#lnk-remote")
                page.wait_for_selector("#remote-tpl h3")
                remote_text = page.locator("#remote-tpl h3").inner_text()
                remote_hits = sum(1 for h in _RouteHandler.hits if h == "/views/computers.html")
                res4 = {
                    "remote_heading": remote_text,
                    "template_http_hits": remote_hits,
                }
                exp4 = {
                    "remote_heading": "外部模板:电脑分类",
                    "template_http_hits": 1,
                }
                cases.append(dict(
                    name="remote_template_url_fetch",
                    expected=exp4,
                    actual=res4,
                    passed=(res4 == exp4),
                ))
            finally:
                browser.close()
    finally:
        srv.shutdown()
        srv.server_close()

    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 #!/ 路由与 otherwise 重定向(服务端根请求保持 1 次)、1.6 前后哈希前缀解析、text/ng-template + controller + resolve 注入及远程 views/computers.html 按需拉取。
离线 Chromium 环回服务实测 Hashbang 路由切换、内嵌模板与远程 templateUrl

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

当前源码 SHA256:5f733e7be5c00bfd1595d3a2f650725d17180c371db229bee60a7a6d782d6f7f

下载本站示例源码

本地运行

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

下载AngularJS 路由实验

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

ZIP SHA256:fd9fef0e8c163e8277920393f1313aac3a15119f4557a4eae3ede3f17d6730e1

常见错误与边界

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

练习与解答

为什么点击不同的 #!/ 路由链接不会触发整页刷新?$routeProvider 配置对象中 template 与 templateUrl 有何区别?

展开参考解答

浏览器不会把 # 之后的 URL 片段提交给服务器,只会触发前端 hashchange 事件,由 ngRoute 拦截并替换 ng-view 中的 DOM;template 直接内联简短 HTML 字符串,templateUrl 则按路径从 $templateCache(如 text/ng-template)或服务端异步拉取外部 HTML 模板。

规范与官方依据