问题描述
我想通过 UI-Router 中的 $state.go()
将自定义对象传递给另一个状态.
I want to pass a custom object to another state via $state.go()
in UI-Router.
var obj = {
a: 1,
b: 2,
fun: function() {
console.log('fun');
}
}
$state.go('users', obj);
但是我需要在目标状态下运行 fun()
,所以我不能在 URL 参数中传递这个对象.在目标控制器中,我尝试通过 $stateParams
获取 obj
的值,但得到了空对象 {}
:
But I need to run fun()
in target state, so I can't pass this object in URL parameter. In target controller, I tried to fetch the value of obj
via $stateParams
but got empty object {}
:
function UserCtrl($stateParams) {
console.log($stateParams); // will be empty
}
那么如何正确传递obj
来声明用户"呢?
So how to pass obj
to state "users" correctly?
推荐答案
使用如下参数定义状态:
Define state with parameters like this:
$stateProvider
.state('user', {
url: '/user',
params: {
obj: null
},
templateUrl: 'templates/user.html',
controller: 'UserCont'
})
当像这样调用传递参数时:
when calling pass parameter like this:
$state.go('user',{obj: myobj});
在控制器 UserCon 中接收参数如下:
in the controller UserCon receive parameter like:
$state.params.obj
用户 $state 是控制器中定义的参数之一
User $state is one of the parameter in the controller defined like
function UserCon($scope, $http, $state){
这篇关于如何在 angular-ui-router 中的 $state.go() 中传递自定义数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!