Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access dynamic segment in a controller in Ember.js?

Tags:

ember.js

I have an example route:

this.route('client', {path: ':id'});

I can access this in my route like this:

model: function(params) {
    console.log(params.id);
}

How do I access the :id in my controller?

like image 594
Melvin Avatar asked Aug 11 '14 06:08

Melvin


3 Answers

This is how I do it in my application. Not sure if this is the best approach.

App.IndexRoute = Em.Route.extend({
  model: function(params) {
    this.set('params', params);
  },
  setupController: function(controller, model) {
    controller.set('params', this.get('params'));
    this._super(controller, model);
  }
});

Alternatively you can also do a lookup on the container inside your controller. But I dont really think this is a good approach. Here is an example.

this.get('container').lookup('router:main').router.currentHandlerInfos
        .findBy('name','index').params
like image 54
blessanm86 Avatar answered Nov 11 '22 00:11

blessanm86


There's a serialize function within the Route that you can take advantage of. Here's the API Documentation for it. However, in your context, you can just do this:

App.IndexRoute = Em.Route.extend({
  model: function(params) {
    console.log(params.client_id);
  },
  serialize: function(model){
    return { client_id : model.id };
  }
});

Let me know if this works!

I also noticed an error in your route definition. It should presumably be

this.route('client', {path: '/:client_id'});

or

this.route('client', {path: '/client/:client_id'});
like image 24
abuani Avatar answered Nov 11 '22 02:11

abuani


If your id happens to be part of your model you can retrieve from the model itself. For example, if you have a route with an object Bill as a model, and the path bills/:billId, on your controller you can retrieve it this way:

this.get('model').id

like image 34
Mirna De Jesus Avatar answered Nov 11 '22 01:11

Mirna De Jesus