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/angularjs@1.0.22/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后
    在这里插入图片描述
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值