awwester
awwester

Reputation: 10162

Pass data from application controller to child controller

I'm using Ember 1.13, I think some of this has been deprecated/changed in 2.x, but this project will not be upgraded.

Maybe I'm not going about this the right way, or missing something simple. Either way, what I need to do is add a new drink in a modal and then update the menu data with that new drink (as a row in a table).

I have a menu controller inside a parent admin controller (admin.menu). I have a modal where I'm adding data, and the modal seems to need to be in the application controller outside of any outlet, or else it does not render correctly. So, I'm adding the new drink within an action in the application controller.

// controllers/application.js
export default Ember.Controller.extend({
  menuController: Ember.inject.controller('admin.menu'),

  ...

  actions: {
    submitCustomDrink: function(){
      // action to create a new custom drink item
      let element = document.getElementById("custom-drink-name");
      let drinkType = element.value;

      Ember.$.ajax({
        'url': `${Config.apiRoot}store-drinks/custom/`,
        'method': 'POST',
        'data': {
          drink_name: drinkType
        }
      }).then(data => {
        // Add new drink to the existing drinks list
        let drinkArray = this.get("menuController.drinkArray");
        let drinkObject = {
          "drinkType": drinkType,
          "drinkSet": data
        };

        drinkArray.push(drinkObject);

        data.forEach(drink => {
          this.store.push('store-drink', drink);
          console.log(`pushed ${drink.type} of ${drink.size} into store`);
        });

        // reset modal input
        element.value = "";
      }, function(err){
        console.log('error', err);
      });
    }
  }
});

In that application controller, I'm injecting the menu controller which uses the data that I'm adding.

When I add a new drink, I'm expecting a table in templates/admin/menu.hbs to have an extra row. The rows are generated from a component that uses the drinkArray from the controller.

<tbody>
{{#each drinkArray as |drink|}}
  {{joe-menu-row drinkSet=drink.drinkSet type=drink.drinkType detailDrink=detailDrink}}
{{/each}}
</tbody>

Upvotes: 0

Views: 43

Answers (1)

Alisdair McDiarmid
Alisdair McDiarmid

Reputation: 368

It's hard to say for sure without a full code sample, but it looks like your problem might be using push instead of pushObject. The latter will trigger observers and dependencies, which will cause your template to rerender.

You may also want to look into ember-wormhole as a way of rendering a modal dialog into the top-level application template, without having to do so from the application controller.

Upvotes: 0

Related Questions