Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
864 views
in Technique[技术] by (71.8m points)

angularjs - How to pass custom data in $state.go() in angular-ui-router?

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);

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
}

So how to pass obj to state "users" correctly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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});

in the controller UserCon receive parameter like:

$state.params.obj

User $state is one of the parameter in the controller defined like

function UserCon($scope, $http, $state){

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...