AngularJS: Read route param from within controller

ctitze picture ctitze · Apr 28, 2013 · Viewed 12.9k times · Source

How can a parameter from an URL be read within an AngularJS controller?

Let's say I have an URL like http://localhost/var/:value and I want the value to be stored in a variable within the controller for the /var/:value URL.

I have tried using $routeParams.value and $route.current.params.value but $routeParams is undefined at the beginning and $route doesn't work.

Answer

Martin picture Martin · Apr 28, 2013

The problem is that you probably inject $routeParams or $route in a controller that is run before a route change has occurred, e.g. your main/master/page controller.

If you inject $routeParams in a controller for a specific route (specified by the controller property when you define the route), then it will work, otherwise you're probably better of listening to the various events the route service broadcasts.

Try to change your code to use

$scope.$on('$routeChangeSuccess', function (ev, current, prev) {
   // ... 
});