天天看點

AngularJs ui-router路由跳轉傳參

1、在跳轉a标簽中通過跳轉指令設定
		ui-sref='state名稱({鍵值對1,鍵值對2})'
			其中,值如果是變量會自動解析,如果是字元串需要加""

2、在對應state路由中設定
		在url路徑後添加"/{鍵名}/{鍵名}"

3、讀取參數
	在對應的controller中,注入$stateParams
		$stateParams.鍵名調用
           

代碼示例:

<html ng-app="app" ng-controller="main">
<head>
	<meta charset="utf-8">
	<title ></title>
	
	<script src="js/libs/angular.js"></script>
	<script src="js/libs/angular.route.min.js"></script>
	<script src="https://cdn.bootcss.com/angular-ui-router/1.0.25/angular-ui-router.js"></script>
 <style>
	.a{
		color:red;
	}
 </style>
	
</head>

<body>
<div ng-controller='d1'>
	<a href="#">首頁</a>
	<a href="#/home">home</a>
	//傳入參數
	<a href="" ui-sref='movie({sex:"male",age:"18"})'>movie</a>
	<a href="" ng-click="go('home')">跳轉到home</a>
	<!-- 當通路路由出錯,會顯示内容 -->
	<div ui-view>頁面不存在</div>
</div>



<script>
var app=angular.module('app',['ui.router']);

app.config(['$stateProvider','$urlRouterProvider',function($stateProvider,$urlRouterProvider){

		//将'/hd'設定為預設頁,打開頁面自動跳轉
		$urlRouterProvider.otherwise('');

		//建立路由
		$stateProvider.state('default',{
			//路徑為空表示在目前頁面
			url:'',
			template:'<h1>哈哈</h1>'
		})
		.state('home',{
			url:'/home',
			template:'<h1>home{{name}}</h1>',
			//控制器
			controller:['$scope',function($scope){
				$scope.name='jeff'
			}]
		})
		.state('movie',{
		//接收參數
			url:'/movie/{sex}/{age}',
			templateUrl:'./angular/user.html',
			controller:'movieCon'

		})

}])


app.controller('main',['$scope',function($scope){

}])

app.controller('d1',['$scope','$state',function($scope,$state){

	$scope.go=function(url)
	{
		$state.go(url);
	}
}])

app.controller('movieCon',['$scope','$stateParams',function($scope,$stateParams){
	$scope.age=17;

	$scope.user=[
	{id:1,name:'jeff'},
	{id:2,name:'mike'}
	]
	//讀取參數
	console.log($stateParams.sex,$stateParams.age)

}])







</script>

</body>
</html>