Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 864
victorwoo Avatar asked May 11 '15 10:05

victorwoo


1 Answers

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){
like image 77
Srini Avatar answered Oct 12 '22 07:10

Srini