在這里分享我做的一個使用ui-router 傳參的小demo
1.首先第一步設(shè)置入口文件index.html,注意加載的順序,先加載包,再加載自己寫的控制器。
<!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文件,依賴注入,設(shè)置路由,此處的路由是使用ui-router路由,這里簡單的演示了兩個模板之間的傳參,傳遞參數(shù)的模板test.html和接收參數(shù)的模板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', {//模板的參數(shù) url: '/index',//url的參數(shù) templateUrl: 'templates/test.html',//模板的位置 controller: 'MyController' }) .state('result', { url: '/result/:id/:number',//需要傳的參數(shù)的鍵名 templateUrl: 'templates/result.html', controller: 'resultCtrl' });});3.第一個主頁面的模板test.html,并且設(shè)置點(diǎn)擊事件toResult()
<meta charset="UTF-8"><div>hello world</div><input type="button" ng-click="toResult()" value="toResult">
4.test.html的控制器indexCtrl.js,設(shè)置需要傳遞的參數(shù)$scope.abc和$scope.toResult,點(diǎn)擊事件toResult()里面其實(shí)就是一個$state.go('模板的參數(shù)',{app.js里面需要傳的參數(shù)的鍵名:需要傳的參數(shù)值})的方法
routerApp.controller('MyController', function($scope, $state) { $scope.abc = "nice";//需要傳的參數(shù)值 $scope.def = 10;//需要傳的參數(shù)值 $scope.toResult = function(){ $state.go('result',{id: $scope.abc,number: $scope.def}); }});5.接收參數(shù)的模板result.html
<meta charset="UTF-8"><div>hello world2</div>
6.result.html的控制器resultCtrl.js,這里使用$stateParams的方法去接收上一個頁面?zhèn)鬟f過來的參數(shù)
routerApp.controller('resultCtrl', function($scope, $state, $stateParams) { var id = $stateParams.id; var number = $stateParams.number; console.log(id); console.log(number);});
新聞熱點(diǎn)
疑難解答
圖片精選