Search code examples
ember.jsmodelcontrollerember-data

How to access model data in Ember controller


I'm mainly new in Ember. I want to access model data in my controller. I'm using Ember.RSVP.hash to load multiple of models in my route.

my route

 model(params) {
   this.set('id', params.userID);
   return Ember.RSVP.hash({
     dashboards: this.store.findAll('dashboard', params)
      .then((dashboards) => dashboards.toArray()),
     user: this.store.find('user', params.userID)
    })
  },
  setupController(controller, model) {
    controller.setProperties(model);
  },

user model

export default DS.Model.extend({
  userID: DS.attr('string'),
  email: DS.attr('string'),
  name: DS.attr('string'),
  picture: DS.attr('string'),
  active: DS.attr('boolean'),
  permissions: DS.attr(),
  created: DS.attr('utc'),
  password: DS.attr('string')
});

Then I'm trying to access one of the user model parameters. In my controller I created init function and I tried to access user model parameter. What I wrote:

  init() {
    console.log(this.get('user.name'));
  },

After that I got undefined. What is the proper way of doing that?


Solution

  • You should not access it init method. You can access it in a template using {{model.user}}.

    • findAll - you don't need to pass params argument you got it from model hook.
    • find is deperecated, use query or queryRecord
    • then should return the value like (dashboards) => return dashboards.toArray()
    • You dont need to override setupController since by default it will set model hook return values in controller.
    • Just ensure data is loaded in store by using Ember inspector.

    Prepared twiddle for basic demonstration