0
点赞
收藏
分享

微信扫一扫

uiRouter之路由传参

Alex富贵 2022-01-26 阅读 54

例子

代码

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.6.8/angular.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/angular-ui-router/1.0.30/angular-ui-router.min.js"></script>
  </head>
  <body>
    <div ng-app="myApp" ng-controller="myCtrl">
      <h1>{{indexName}}</h1>
      <div class="router-content">
        <!-- 5. 定义改变视图的的按钮 -->
        <!-- sref中你只能使用state名,加上一些参数 -->
        <a ui-sref="R1({id:4,number:5})">R1</a><br>
        <button ng-click="goR2()">R2</button>
        <button ng-click="goR3()">R3</button>
        <!-- 2. 定义视图 -->
        <div ui-view></div>
      </div>
    </div>
    <script>
      // 1. 注入相关的模块
      var app = angular.module("myApp", ["ui.router"]);
      app.controller("myCtrl", function ($scope,$state) {
        $scope.indexName = "主页";
        $scope.goR2 = function(){
          // 传递参数
            $state.go("R2",{id:2,number:5})
        };
        $scope.goR3 = function () {
          $state.go("R3",{id:6,number:6});
        }
      });
      // 3. 配置路由,注意传入$stateProvider
      app.config(function($stateProvider){
          // 4. 定义两个路由
          /*
          从R1跳转到R2并将R1的参数传过去
          */
          $stateProvider.state("R1",{
            url:"R1?id&number", // 参数声明
            template:"<h1>Hello</h1>",
            controller:function($scope,$stateParams){
              console.log($stateParams);
            }
          });
          // 在路径中映射参数
          $stateProvider.state("R2",{
            url:"R2/:id/:number", // 参数声明
            template:"<h1>World</h1>",
            controller:function($scope,$stateParams){
              console.log($stateParams);
            }
          });

          $stateProvider.state("R3",{
            url:"R3", // 参数声明
            template:"<h1>World_R3</h1>",
            controller:function($scope,$stateParams){
              console.log($stateParams);
            },
            // 参数声明
            params:{
              id:null,
              number:null
            }
          });
      })
    </script>
  </body>
</html>

效果

  • 点击R1
    在这里插入图片描述

  • 点击R2在这里插入图片描述

  • 点击R3

在这里插入图片描述

总结

参数声明

  1. 在路由路径中声明,在路径汇总声明有两种方式
    1. 如果在路径中声明,那么在路由跳转的时候路径上会显示相应的参数
  2. 通过params参数进行配置
    1. 参数不会在路径中显示

参数传递

  1. 所有路由携带的参数都会在$stateParams中保存,注意在这里不同方式所传的数据的类型不同
  2. 在控制器中,可以使用$state.go()的第二个参数进行传参,在模板汇总可以使用状态({参数}),来进行传参
举报

相关推荐

路由传参

vue路由传参

Vue路由传参

vue 路由传参

django 路由传参

React 路由传参

路由跳转和传参

0 条评论