12

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.

ctitze
  • 691
  • 2
  • 7
  • 17
  • What do you mean by "$routeParams is undefined at the beginning and $route doesn't work"? Could you share code where you've tried to make them work? Both $route.current and $routeParams should give correct results in a controller provider that you've set up routes and injected dependencies into a controller. – pkozlowski.opensource Apr 28 '13 at 15:27

2 Answers2

15

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) {
   // ... 
});
Martin
  • 8,876
  • 2
  • 35
  • 36
  • 1
    You're absolutely right, the controller is run before a route change has occurred because the client is directly calling the URL when connecting. But your posted code doesn't work because there's no route change. Any other suggestions to solve this problem? – ctitze Apr 29 '13 at 05:59
  • 3
    If your clients hits the url directly without you letting AngularJS handle the routing then you won't be able to use `$routeParams`. `$routeParams` only work if you're using `$routeProvider.when(/movies/:genre, { ... })`, otherwise you have to extract the values manually. Question: are you using AngularJS routing or are you simply looking for a way to extract values from the url? – Martin Apr 29 '13 at 08:06
  • I'm using AngularJS for routing because I want to load different `templateUrls` in my `ng-view` (angular-express-seed). But thanks for the answer, seems that I need to solve my problem with a different approach. – ctitze Apr 29 '13 at 12:20
  • Had the same issue, I was trying to reference $route.current.controller and it was undefined in a controller on the "master" page before the actual ng-view route was populated. Thanks for the explanation! – James Eby Sep 25 '13 at 18:49
3

Requirements: Ensure 'ngRoute' is in your app module

Route provider set up as: http://localhost/var/:valName

Function set up as:

function functionName($scope, $routeParams){$scope.value = $routeParams.valName;}

HTML view:

{{value['valName']}}
adswebwork
  • 5,245
  • 3
  • 19
  • 9