Jayson Bailey
Jayson Bailey

Reputation: 1004

Rails route params in angular

I'm playing around with angular in my rails app. This is not a single page app, i'm just using angular in a few places. I'm having a hard time getting route params from the uri to use in my resources.

For instance, say I'm on the page /users/1/posts/2. How do I get both user_id and id(for post)?

Thanks.

Upvotes: 1

Views: 742

Answers (3)

Joshua Book
Joshua Book

Reputation: 157

You could configure your angular app to pass the params to the controller your using for that page.

I would make a routes.js file doing something like:

App.config(['$routeProvider', function($routeProvider){
  $routeProvider
  .when('/your-route', {
    controller: 'yourNGController',
    resolve: {
      params: ['$route', function($route){
        params = {user_id: $route.current.params.user_id}
        params.merge({post_id: $route.current.params.post_id})
        return params
      }]
    }
  })
}])

Then in your controller - "yourNGController' inject 'params' that you resolved in your route. That should get your the info you need into the controller.

If using newer versions of angular you may also need to include the angular-route.js as $routeProvider was removed from the core angular components.

Upvotes: 1

port5432
port5432

Reputation: 6381

I had a similair issue, and it is linked here: Passing Rails ID to Angular

I consider this solution a bit of a hack, so am interested in better approaches.

Upvotes: 0

Jayson Bailey
Jayson Bailey

Reputation: 1004

I ended up just using ui-routes which makes this problem a whole lot easier.

Upvotes: 0

Related Questions