Girja Shanker
Girja Shanker

Reputation: 85

How to access the params in controller ember.js

This is my router.js code.

this.route('contact',{'path': '/contact/:chat_id'});

and This is my route.js code.

model(params) {

  return this.store.findRecord("chat", params.chat_id)
},

and This is my controller.js code and can i use like this. It shows error as null value please help me. How to use params in controller

recordChat: function() {

  var chat = this.get(params.chat_id)

  Ember.RSVP.hash({
    offer_id: chat,
  })
}

Upvotes: 7

Views: 8729

Answers (3)

Cameron
Cameron

Reputation: 2965

Edited for 2021: There's actually probably a much simpler way to do this now in Ember. See https://guides.emberjs.com/v3.27.0/routing/query-params/

Original Answer

I think the simplest answer is to create a variable in route and then set it in the setupController:

your_route.js

export default Ember.Route.extend({
  model(params) {
    this.set('myParam',params.my_Params);
    
    // Do Model Stuff...
  },
  setupController(controller, model) {
    // Call _super for default behavior
    this._super(controller, model);
    // Implement your custom setup after
    controller.set('myParam', this.get('myParam'));
  }
});

Upvotes: 8

Mirna De Jesus
Mirna De Jesus

Reputation: 209

I think you can fetch the id you want from the model because you used the parameter chat_id to find the record and that id is now part of your chat object (which is the route model itself).

So, in your controller you just need to do: this.get('model').id

Upvotes: 0

Remi Smirra
Remi Smirra

Reputation: 2539

In your route.js, you need to call the setupController function like this:

setupController(controller, model) {
    this._super(...arguments);
    controller.set('chat', model);
}

Now you have access to it in your controller by calling:

recordChat() {
   const chat = this.get('chat');
   //  if you don't call the setupController function, you could also do:
   // const chat = this.get('model') or this.get('model.id') if you want the id only
}

UPDATE:

See working twiddle here

Upvotes: 3

Related Questions