简体   繁体   中英

Ember Model empty until enter Route

I have an Ember App with Models for:

  • Food
  • Meals

(there are other Models but these are ommitted for the sake of brevity).

The router is configured thus:

this.resource('food', { path: '/food/:food_id' });

this.resource('meals',function() {
  this.resource('meal', { path: '/:meal_id'}, function() {
    this.route('edit');
  });

  this.route('new');
});

In my Food template I need access to the list of Meals in order to print them. Initially I thought of the needs property on the FoodController would do the trick.

App.FoodController = Ember.ObjectController.extend({
    needs: ['meals', 'mealsIndex'],
    ...
});

In my template I then tried

{{#each meal in controllers.meals.content}}
    TEST
{{/each}}

...but nothing is displayed. I've actually tried several other methods but nothing is having any effect.

I suspect that perhaps the the MealsController's Model isn't being set until the meals route is entered.

I'm totally stuck here and the docs aren't helping. Any assistance much appreciated.

You'll need to request the models from the server manually, like this:

App.FoodRoute = Ember.Route.extend({
    model:function(params){
        var store = this.store;
        return Ember.RSVP.hash({
            food:store.find('food',params.food_id),
            meals:store.find('meals')
        });
    },
    controllerSetup:function(controller,models) {
       controller.set('model',models.food);
       this.controllerFor('meals').set('model',models.meals);
    }
});

When your app enters the Food route, it'll request both the current food and all the meals. Then it'll set the model for the food controller and all the meals as the model on the meal controller. You should be able to access them in your template as you have set up using needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM