Search code examples
ember.jsember-cli

How to access model from controller?


I can't seem to get the model from inside the controller, even though the controller seems to have a model property set. The following:

export default Ember.ObjectController.extend({
    init: function() {
        this._super();
        console.log(this.get('model'));
        console.log(this.model);
        console.log(this);
    }
}

prints out:

enter image description here

Any ideas?


Solution

  • The an Ember.ObjectController is a proxy for the model. So the model can be referenced using this as you found in your example. So then in a template {{this.aModelAttr}} or just {{aModelAttr}}. Like you question suggests it's a bit confusing.

    The ObjectController is being deprecated as of Ember 1.11.0. So to simplify use Ember.Controller and in your controller you can reference the model by this.get('model')

    Then in the template use {{model.aModelAttr}}

    To give the model a domain specific ie: books or user name use

    export default Ember.Controller.extend({
        domainSpecificName: Ember.computed.alias('model')
    }
    

    Then in your templates you can use {{domainSpecificName.aModelAttr}}