How do I get the the model to load without going to the route first?
App.UsersRoute = Em.Route.extend({
model: function() {
return ['bob', 'sue', 'tom'];
},
setupController: function(controller, model) {
controller.set('model', model);
}
});
From another controller using
needs: "users"
and
this.get('controllers.users.content');
works fine as long as I visit the UsersRoute first.
Load it in the topmost route that will need it, thusly:
App.SomeOtherRoute = Em.Route.extend({
setupController: function(controller, model) {
controller.set('model', model);
this.controllerFor('user').set('model', ['bob', 'sue', 'tom']);
}
});
Note that if you are using ember-data or epf or ajax, that the model will be a promise. You can't set the model on a controller to be a promise so you would do:
setupController: function(controller, model) {
controller.set('model', model);
return this.get('store').findAll('user').then(function(users) {
this.controllerFor('users').set('model', users);
});
}
Note in the second one I'm using UsersController, not UserController, because you seem to want a collection of users not a single user.
I hit this same problem this past weekend and the following worked for me:
App.SomeOtherController = Ember.Controller.extend({
needs: ['users']
});
App.SomeOtherRoute = Ember.Route.extend({
setupController: function( controller, model ){
this._super( controller, model );
controller.set( 'controllers.users.model', ['bob', 'sue', 'tom'] );
}
});
if it is an ajax call / ember data then you need something like this:
App.SomeOtherController = Ember.Controller.extend({
needs: ['users']
});
App.SomeOtherRoute = Ember.Route.extend({
setupController: function( controller, model ){
this._super( controller, model );
this.get('store').findAll('user').then(function(users) {
controller.set( 'controllers.users.model', users );
});
}
});
However, a colleague pointed out to me during our code review today that if I need to do this I have probably structured my routes / resources / models incorrectly. In other words an outer route should not depend on an inner route's model. So I am now thinking about going back and refactoring this so that the users model is part of the model for the outer route and then I can use that in my inner route controller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With