Animal Rights
Animal Rights

Reputation: 9407

Accessing routeparams from multiple controllers in AngularJS

In my routes, I have it set up so that Controller1 gets called for the route '/:id' which controls one section of the page. However, I also need the :id route param in Controller2. How can I access that information in Controller2 as well?

I am using the $routeProvider service to access the route params in Controller1. This returns an empty object in Controller2.

EDIT:

I created a demo to illustrate my problem better. I want to access $routeParams from 2 controllers but it is only getting recognized by Controller2.

https://dl.dropboxusercontent.com/u/11600860/angular/index.html#/4445

If you look in the console, routeParams is only getting logged into the console by Controller2, not Controller1. Any idea?

Upvotes: 1

Views: 1003

Answers (2)

dpdearing
dpdearing

Reputation: 1726

Your demo no longer exists, but I had what sounds like a similar problem and found a related answer at AngularJS: Read route param from within controller. The general issue (in my case) was that $routeParams is not yet loaded when the controller initially loads and tries to access individual values.

To get around this, I was able to execute a controller method on ng-init, at which point I could successfully access any of the $routeParams.

Upvotes: 1

jszobody
jszobody

Reputation: 28959

Look at the $routeParams service, this should give you what you need. I'm currently injecting it into multiple controllers on a page and accessing the :id param as easily as $routeParams.id.

Upvotes: 0

Related Questions