我需要使用ui-router的ui-sref
向我想转接的状态传递和接收两个参数。
类似于使用下面的链接,用foo
和bar
参数将状态转换到home
。
<a ui-sref="home({foo: 'fooVal', bar: 'barVal'})">Go to home state with foo and bar parameters </a>
在控制器中接收foo'和
bar'值。
app.controller('SomeController', function($scope, $stateParam) {
//..
var foo = $stateParam.foo; //getting fooVal
var bar = $stateParam.bar; //getting barVal
//..
});
我在控制器中为$stateParam'得到
undefined'。
谁能帮我了解一下如何完成?
编辑:
.state('home', {
url: '/',
views: {
'': {
templateUrl: 'home.html',
controller: 'MainRootCtrl'
},
'A@home': {
templateUrl: 'a.html',
controller: 'MainCtrl'
},
'B@home': {
templateUrl: 'b.html',
controller: 'SomeController'
}
}
});
我已经创建了一个例子来展示如何。更新的 "状态 "定义将是。
$stateProvider
.state('home', {
url: '/:foo?bar',
views: {
'': {
templateUrl: 'tpl.home.html',
controller: 'MainRootCtrl'
},
...
}
这将是一个控制器。
.controller('MainRootCtrl', function($scope, $state, $stateParams) {
//..
var foo = $stateParams.foo; //getting fooVal
var bar = $stateParams.bar; //getting barVal
//..
$scope.state = $state.current
$scope.params = $stateParams;
})
我们可以看到的是,现在状态主页的网址定义为。
url: '/:foo?bar',
这意味着,url中的参数被期望为
/fooVal?bar=barValue
这两个链接将正确地将参数传入控制器。
<a ui-sref="home({foo: 'fooVal1', bar: 'barVal1'})">
<a ui-sref="home({foo: 'fooVal2', bar: 'barVal2'})">
另外,控制器确实消耗了$stateParams
而不是$stateParam
。
链接到文档。
你可以检查它这里
还有一个新的,更细化的设置params : {}
。正如我们已经看到的,我们可以将参数作为url
的一部分来声明。但是通过params : {}
配置--我们可以扩展这个定义,甚至引入不属于url的参数。
.state('other', {
url: '/other/:foo?bar',
params: {
// here we define default value for foo
// we also set squash to false, to force injecting
// even the default value into url
foo: {
value: 'defaultValue',
squash: false,
},
// this parameter is now array
// we can pass more items, and expect them as []
bar : {
array : true,
},
// this param is not part of url
// it could be passed with $state.go or ui-sref
hiddenParam: 'YES',
},
...
可用于参数的设置在$stateProvider的文档中描述。
下面只是一个摘录
我们可以这样调用这些参数。
// hidden param cannot be passed via url
<a href="#/other/fooVal?bar=1&bar=2">
// default foo is skipped
<a ui-sref="other({bar: [4,5]})">
在行动中检查它这里
你不一定需要把参数放在URL里面。
例如,用。
$stateProvider
.state('home', {
url: '/',
views: {
'': {
templateUrl: 'home.html',
controller: 'MainRootCtrl'
},
},
params: {
foo: null,
bar: null
}
})
你将能够向状态发送参数,使用以下两种方式之一。
$state.go('home', {foo: true, bar: 1});
// or
<a ui-sref="home({foo: true, bar: 1})">Go!</a>
当然,如果你在 "home "状态下重新加载页面,你将失去状态参数,因为它们没有被存储在任何地方。
关于这种行为的完整描述记录在这里,在state(name, stateConfig)
部分的params
行中。