angularjs $routeParams.x giving me a value of undefined

1,568 views
Skip to first unread message

Ocajian

unread,
Nov 9, 2015, 8:04:56 AM11/9/15
to AngularJS
Hi Everyone

I set up my routing as follows:

.when('/:countryName/:categoryName', {
    templateUrl
: 'views/about.html'
 
})


Problem is, I am having trouble pulling the values from my $routeParams object

For example when I do this:

$scope.parameters = $routeParams;

$scope.parameters equals the following object 
{"countryName":"Japan","categoryName":"Football"}


However if I try assign the following:

$scope.parameters = $routeParams.countryName;

$scope.parameters is undefined

Why is this? What am I doing wrong? I have read the documentation and can't for the life of me see what I am doing differently to the documentation.


Sander Elias

unread,
Nov 9, 2015, 11:28:09 AM11/9/15
to AngularJS
Hi Ocajian,

Can you reproduce this in a plunker? That makes it easier to help you

Regards
Sander


Ocajian

unread,
Nov 10, 2015, 1:04:34 AM11/10/15
to AngularJS
Sure thing! Here is a plunker illustrating my issue - http://embed.plnkr.co/TAHOBq5XGUUQQFY8KI5p/preview 

Sander Elias

unread,
Nov 10, 2015, 1:44:19 AM11/10/15
to AngularJS

HI Ocajian,

Ah, I see what your issue is. When your controller is initialized, you are putting in $scope.parameters = $routeParams;. As $routeParams is an object this will be assigned per reference binding. If any of the properties of $routeParams will change, this will get reflected in $scope.parameters

However, on init, $routeParams.countryName will be undefined. (it is not there yet). So, you assign undefined to $scope.parametersCountr. Undefined is a primitive, and will get assigned per value.

That’s why your seemingly impossible ting happens. $routeParams will receive its properties in after the controller gets initialized.

Does that explain it enough for you?

Regards
Sander

Reply all
Reply to author
Forward
0 new messages