kamrza
kamrza

Reputation: 25

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?

Upvotes: 2

Views: 3699

Answers (2)

Ember Freak
Ember Freak

Reputation: 12872

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

Upvotes: 1

ykaragol
ykaragol

Reputation: 6221

Use this.get('model') on your controller to access your model data as a whole. You can also use Ember.get(this, 'model.user.name');. You can use something like these: look at the actions.

But init is an eager hook! model property has not been set yet at init hook!

Upvotes: 4

Related Questions