Prakash Raman
Prakash Raman

Reputation: 13923

What is the correct way to access the model from a controller in Ember

I was wondering what the correct way to access the model from the controller?

I noticed that in the init of the controller the model is still null

#controller.js

init(){
  console.log(this.model); // IS NULL
}

But the setupController method has the populated model. Therefore currently I am calling a controller's method from the setupController and an passing the model over there. Is this fine?

I was thinking there would be a callback method in the controller which would automatically be called when the controller is setup.

Upvotes: 0

Views: 1243

Answers (2)

Sedad Kosovac
Sedad Kosovac

Reputation: 668

route.js

  model() {
    return this.store.findAll("post");
  },  
  setupController(controller, model){
    controller.set('model', model);
  }

This will give console log model which is collection of post object.

controller.js

 init(){
  console.log(this.model);
 }

We do this most of the times especially if you use RSVP promise you chose what will be the model on your controller.

Example

 model(params) {
    return Ember.RSVP.hash({
      lecture: this.store.findRecord('section', params.section_id).then((section)=>{
        return this.store.createRecord('lecture',{
          section: section
        });
      }),
      section:this.store.findRecord('section', params.section_id),
      course: this.store.query('course',{filter:{section_id:params.section_id}})
    });
  },
  setupController(controller,model){
    controller.set('model', model.lecture);
    controller.set('section', model.section);
    controller.set('course', model.course);

  }

Note if you only have just simple model on route

 model(params) {
        return this.store.findRecord('course', params.course_id);
      }

and you don`t have to do any setup on controller which is possible this will also give you model on controller.

Upvotes: 4

Ember Freak
Ember Freak

Reputation: 12872

setupController hook method will set model as property to controller.

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

You can get model just like normal other properties in controller. this.get('model')

Upvotes: 2

Related Questions