原文地址:http://www.ncloud.hk/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/ui-router-transmit-params/
有時間我們需要把一個頁面的參數傳到另一個頁面,供另一個頁面使用。下面講一下利用路由傳參的方法。
例如有兩個頁面:page1.html和page2.html,點擊page1.html跳轉到page2.html,並將page1.html的參數傳遞過去。
(1)在app.js中定義路由信息,並在接收的頁面(即page2.html)定義接收參數。
.state('page1', {
url: '/page1',
templateUrl: 'templates/page1.html',
controller: 'pageOneCtrl'
})
.state('page2', {
url: '/page2',
templateUrl: 'templates/page2.html',
controller: 'pageTwoCtrl',
params:{'ID':{}}
})
(2)在page1中定義點擊事件。
html中:ng-click=“toPage2(id)”
控制器中:
.controller('pageOneCtrl', function ($scope, $state) {
$scope.toPage2 = function (id) {
$state.go('page2', {ID:id});
};
});
(3)在Page2中通過$staeParams獲得參數ID。
.controller('pageTwoCtrl’, function ($scope, $state, $stateParams) {
var receivedId = $stateParams.ID;
console.log(receivedId);
//打印的結果即為id
});
這樣就可以成功傳遞參數了。如果需要傳遞多個參數,
(1)在app.js中定義路由信息,並在接收的頁面(即page2.html)定義接收參數。
.state('page1', {
url: '/page1',
templateUrl: 'templates/page1.html',
controller: 'pageOneCtrl'
})
.state('page2', {
url: '/page2',
templateUrl: 'templates/page2.html',
controller: 'pageTwoCtrl' ,
params:{args:{}}
})
(2)在page1中定義點擊事件。
html中:
ng-click=“toPage2(name,number)”
控制器中:
.controller('pageOneCtrl', function ($scope, $state) {
$scope.toPage2 = function (name,number) {
$state.go('page2', {
args:{
NAME:name,
NUMBER:number
});
};
});
(3)在Page2中通過$staeParams獲得參數ID。
.controller('pageTwoCtrl’, function ($scope, $state, $stateParams) {
var receivedName = $stateParams.args.NAME;
var receivedNumber = $stateParams.args.NUMBER;
});
