Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular $routeParams returns empty object

I've been stuck for about a day on a problem that I can't see through.

I have the following code in a users.js.coffee file:

app = angular.module("app", ["ngResource"])
app.config ['$routeProvider', '$locationProvider', ($routeProvider, $locationProvider) ->
  $locationProvider.html5Mode(true)
  $routeProvider.when('/users/:id', {templateUrl: '/users/:id.json', controller: UserCtrl})
  $routeProvider.when('/users/:id/videos', {templateUrl: '/users/:id/videos.json', controller: UserCtrl})
]

app.factory "User", ["$resource", ($resource) ->
  $resource("/users/:id", {id: "@id"}, {
    show: {method: "GET"}, 
    videos: {method: "GET", isArray:true}
    })
]

@UserCtrl = ["$scope", "$location", "$route", "http", "$routeParams", "User", ($scope, $location, $route, $http, $routeParams, User) ->
  console.log($location)//LocationUrl {$$parse: function, $$compose: function, $$rewriteAppUrl: function, $$protocol: "http", $$host: "localhost"…}

  console.log($route)//Object {routes: Object, reload: function}
  console.log($routeParams)//Object {} 

]

Why would $routeParams be an empty object? If I call $route.current.params in a view, it shows the appropriate parameters. But not in the controller. What's more, I can't call $route.current.params in the controller, because "current" isn't yet defined.

like image 292
jflores Avatar asked Mar 14 '13 03:03

jflores


3 Answers

I had the same problem. The routing won't work if there is no ng-view. Just had a ng-view you'll get your $routeParams.

regards

like image 106
Yop44 Avatar answered Nov 17 '22 01:11

Yop44


If you are using an external controller to the routed-to ng-view controller (like a topbar, or page controller), the you'll need to subscribe to the '$routeChangeSuccess' emit message.

The route change success is asynchronous if you aren't the receiving controller. This SO answer gives a more complete answer: $routeParams is empty in main controller

but this is the tldr;

$scope.$on('$routeChangeSuccess', function() {
  // $routeParams should be populated here
});
like image 2
David Merritt Avatar answered Nov 17 '22 00:11

David Merritt


It looks like $routeParams is not available at controller initialization time to controllers outside of those routed via $routeProvider / ng-view. (At least in angular 1.0.8)

If you want to access the route parameters in those outer controllers you can use $location.search().<param_name>

like image 1
Amir Avatar answered Nov 17 '22 00:11

Amir