当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > AngulaJS路由 ui-router 传参实例

AngulaJS路由 ui-router 传参实例

2018年04月30日  | 移动技术网IT编程  | 我要评论

在这里分享我做的一个使用ui-router 传参的小demo

1.首先第一步设置入口文件,注意加载的顺序,先加载包,再加载自己写的控制器。

<!doctype html>
<html lang="en" ng-app="routerapp">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
  <title>测试</title>
  <!--lib是angular包的文件夹-->
  <script src="lib/jquery/jquery-1.11.3.min.js"></script>
  <script src="lib/angular/angular.js"></script>
  <script src="lib/angular-ui/angular-ui-router.js"></script>
  <!--js控制器的文件夹-->
  <script src="js/app.js"></script>
  <script src="js/indexctrl.js"></script>
  <script src="js/resultctrl.js"></script>
</head>

<body>

<div ui-view>

</div>

</body>

</html>

2.app.js文件,依赖注入,设置路由,此处的路由是使用ui-router路由,这里简单的演示了两个模板之间的传参,传递参数的模板test.html和接收参数的模板result.html

var routerapp = angular.module('routerapp', ['ui.router']);

routerapp.run(function($rootscope, $state, $stateparams) {
  $rootscope.$state = $state;
  $rootscope.$stateparams = $stateparams;
});

routerapp.config(function($stateprovider, $urlrouterprovider) {
  $urlrouterprovider.otherwise('/index');
  $stateprovider
    .state('index', {//模板的参数
      url: '/index',//url的参数
      templateurl: 'templates/test.html',//模板的位置
      controller: 'mycontroller'
    })
    .state('result', {
      url: '/result/:id/:number',//需要传的参数的键名
      templateurl: 'templates/result.html',
      controller: 'resultctrl'
    });
});

3.第一个主页面的模板test.html,并且设置点击事件toresult()

<meta charset="utf-8">
<div>hello world</div>
<input type="button" ng-click="toresult()" value="toresult">

 4.test.html的控制器indexctrl.js,设置需要传递的参数$scope.abc和$scope.toresult,点击事件toresult()里面其实就是一个$state.go('模板的参数',{app.js里面需要传的参数的键名:需要传的参数值})的方法

routerapp.controller('mycontroller', function($scope, $state) {
  $scope.abc = "nice";//需要传的参数值
  $scope.def = 10;//需要传的参数值
  $scope.toresult = function(){
    $state.go('result',{id: $scope.abc,number: $scope.def});
  }
});

5.接收参数的模板result.html

<meta charset="utf-8">
<div>hello world2</div>

6.result.html的控制器resultctrl.js,这里使用$stateparams的方法去接收上一个页面传递过来的参数

routerapp.controller('resultctrl', function($scope, $state, $stateparams) {
  var id = $stateparams.id;
  var number = $stateparams.number;
  console.log(id);
  console.log(number);
});

项目目录

js\app.js、indexctrl.js、resultctrl.js

lib\
jquery\jquery-1.11.3.min.js
angular\angular.js
angular-ui\angular-ui-router.js

templates\test.html、result.html

其实整个过程并不难,只是穿插在模板和控制器之间,容易让人摸不着头脑,只要分清楚具体的参数是对应哪一个,很容易理解。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网