How could I get father controller's model in the son controller?


#1

I defined my route:

this.resource('users', function() {
    this.route('create');
)};

Now I created a new user in UsersCreateController, but how could I update the whole users model? How could I get the model in the UsersController? I didn’t use Ember Data, just simple localStorage. Thank you so much!


#2

There are three ways that I can think of:

  1. Do nothing. This one’s my favorite. :wink: As of Ember 1.5.0, child routes automatically inherit their parent’s model. So your UsersCreateController should already have the parent model as its own model.

  2. The same technique as above, only explicitly declare that you’re inheriting the model:

    App.UsersCreateRoute = Ember.Route.extend({
        model: function() {
            return this.modelFor('users');
        }
    });
    
  3. Use the needs property of the controller:

    App.usersCreateController = Ember.ObjectController.extend({
        needs: ['users'],
        model: Ember.computed.alias('controllers.users.model')
    });
    

#3

Thank you so much! Your answer helped me a lot. By the way, I heard that using usersBinding: ‘controller.users.model’ this way to get the model in the father controller. How about this way? Can I get all the controller’s properties through ‘controllers.XXX.prop’ ? If so, it’s really flexible.


#4

If you use method 3, you already have that binding through the computed alias.

you could also write:

modelBinding: 'controllers.user.model'

or simply use it in you template via handlebars:

{{controllers.user.model}}

There is a cool article. Abit “old”, but nearly all of it works still: http://code418.com/blog/2012/03/26/advanced-emberjs-bindings/