0

I am trying to pass data from one controller to another using $stateParams but getting null instead of valid data:

Please find my route code below:

.state("root.home", {
            url: "/home",
            abstract: true,
            template: homeHtml,
            controller: "HomeCtrl as ctrl",
        })
.state("root.home.content", {
            url: "",
            params: {
                userId: null,
            },
            views: homeView,
        })

Controller A code:

$state.go("root.home.content", {userId}); // getting correct UserId

HomeCtrl code:

// In its constructure I injected the $stateParams

    init() {
            console.log($stateParams); // getting undefined here
            if ($stateParams && $stateParams.userId) {
                this.loadUser($stateParams.userId);
            }
        }
2
  • Have you forgot to inject $stateParams into the controller? Commented Apr 19, 2017 at 14:39
  • Nopes, it is injected. Commented Apr 19, 2017 at 14:59

2 Answers 2

1

Pass your parameter as below

$state.go("root.home.content", {'userId': userId}); 
//This userId should be a valid variable inside your Controller A

And also you should edit your router as below,

.state("root.home.content", {
            url: "/:userId",
            params: {
                userId: null,
            },
            views: homeView,
        })

Otherwise it will not show in the url & cannot access from $stateParams

Sign up to request clarification or add additional context in comments.

6 Comments

This is probably the reason, I just can't understand why console.log($stateParams); is giving them an undefined
I am using ES6 and I think with its property shorthand feature it is not required.
Edited the answer
I am afraid but by doing this will not make any difference as I am injecting params in other controller and handling it in route ("root.home.content"). Not sure but may be I am missing something in the parent route: .state("root.home") as I defined the controller there.
Yes it was showing correctly but I was not getting null for $stateParams.userId in HomeCtrl
|
1

I fixed this by adding params to parent root instead of child. The correct code is:

.state("root.home", {
                url: "/home",
                params: {
                    userId: null,
                },
                abstract: true,
                template: homeHtml,
                controller: "HomeCtrl as ctrl",
            })
.state("root.home.content", {
                url: "",
                views: homeView,
            })

Comments