微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular路由之ui-router

Angular路由之ui-router

说明

上一篇介绍了angular自带的路由的使用,但实际上已经用的很少了,基本被第三方的ui-router取代。二者使用上区别不是很大,之所以前者被取代,是因为ui-router功能更为强大

官网

hello world

  • 自认为最好的入门教程是官方demo

完整代码


<html>
  <head>
    <title>ui-router入门程序</title>
    <script src="https://cdn.bootcss.com/angular.js/1.7.8/angular.min.js"></script>
    <script src="https://unpkg.com/@uirouter/[email protected]/release/angular-ui-router.js"></script>
    <style>.active { color: red; font-weight: bold; }</style>
  </head>
  <body ng-app="helloworld">
<!--  ui-sref-active="active" 会自动匹配当前访问的是哪一个 -->
    <a ui-sref="hello" ui-sref-active="active">Hello</a>
    <a ui-sref="about" ui-sref-active="active">About</a>
<!--  呈递视图,不要忘记加,这个小东西很重要,一个页面可以放多个 -->
    <ui-view></ui-view>
  </body>
  <script>
		//创建应用模块,加载ui.router
    var myApp = angular.module('helloworld', ['ui.router']);
		//配置路由
        myApp.config(function($stateProvider) {
          var helloState = {
            name: 'hello',//状态名,与 ui-sref的值相同
            url: '/hello',//访问地址
            template: '<h3>Hello World!</h3>'//显示内容
          }
          var aboutState = {
            name: 'about',
            url: '/about',
            template: '<h3>Its the UI-Router hello world app!</h3>'
          }
          //挂载路由
          $stateProvider.state(helloState);
          $stateProvider.state(aboutState);
        });
        
  </script>
</html>


在线测试

https://lengyuexin.github.io/ui_router/

补充

  • 既然要用,首先就是引包,可以用cdn方式在线引用,也可以npm或者bower下载到本地用

    在这里插入图片描述


    在这里插入图片描述

  • 注意,你引用的angular版本要和ui-router版本匹配,这里是1.x配1.x

  • $stateProvider.state很智能,支持链式调用,和jquery很像,每次操作结束都返回自身对象

  • $stateProvider.state(helloState).state(aboutState) ,这样写也是可以的

效果

注意地址栏和active的变化

  • 初始界面

    在这里插入图片描述

  • 点击Hello后

    在这里插入图片描述

  • 点击About后

    在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐