最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular $routeParams returns empty object - Stack Overflow

programmeradmin2浏览0评论

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, $$pose: 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.

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, $$pose: 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.

Share Improve this question edited May 17, 2013 at 14:41 TheHippo 63.2k15 gold badges77 silver badges101 bronze badges asked Mar 14, 2013 at 3:30 jfloresjflores 4836 silver badges18 bronze badges 5
  • this is not related to your question, but i don't think you can use to_json when you use respond_with. You have to provide an object, and your controller will call the appropriate responder according to the requested format. – m_x Commented Mar 14, 2013 at 9:05
  • I think you're generally right, unless I need to grab an association like @user.to_json(include: :videos). I just have it there to make it explicit until I can figure out why I'm not getting the appropriate response. – jflores Commented Mar 14, 2013 at 13:29
  • the preferred way to include associations in a json response is to override as_json in your model. As to your problem, can you set your browser to log xhr requests (chrome does it) and post here exactly what es back and forth ? – m_x Commented Mar 14, 2013 at 14:52
  • Ah, you're right. My mistake. I set the browser to log xhr requests and the object returned is a JSON array of all of my users. I'll post an example above (but not the actual user data). – jflores Commented Mar 14, 2013 at 23:51
  • It occurred to me - is it allowed for me to call a JSON object in templateURL? Everything I've read shows partial HTML files being called... – jflores Commented Mar 15, 2013 at 0:09
Add a ment  | 

4 Answers 4

Reset to default 7

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

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 plete answer: $routeParams is empty in main controller

but this is the tldr;

$scope.$on('$routeChangeSuccess', function() {
  // $routeParams should be populated here
});

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>

Your routes are pointing to your api route. They should be a path to the template to render instead:

@App = angular.module('app',['ngResource'])
  .config(['$routeProvider'], ($routeProvider) ->
    $routeProvider
      .when('/users',
        templateUrl: 'users/index.html',
        controller: 'UsersIndexCtrl')
      .when('/users/:id',
        templateUrl: 'users/show.html',
        controller: 'UsersShowCtrl')
      .otherwise(
        redirectTo: '/users'
    )])

Then, say, your users index controller would probably look like:

App.controller 'UsersIndexCtrl',['$scope','$location','User', ($scope, $location, User) ->

  $scope.users = User.query()

  $scope.onClickHandlerToRoute = (user)->
    $location.path "path/to/show/user/#{user.id}"

You don't need to inject $http as you are already using the ngResource REST abstraction.

发布评论

评论列表(0)

  1. 暂无评论