moranje
3/8/2017 - 4:47 PM

nutrient-total

nutrient-total

{
  "version": "0.11.1",
  "EmberENV": {
    "FEATURES": {}
  },
  "options": {
    "use_pods": false,
    "enable-testing": false
  },
  "dependencies": {
    "jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
    "ember": "2.11.0",
    "ember-data": "2.11.0",
    "ember-template-compiler": "2.11.0",
    "ember-testing": "2.11.0"
  },
  "addons": {}
}
<table style="width:100%">
  <tr>
    <th>Group</th>
    <th>Name</th>
    <th>Weight</th>
  </tr>
  {{#each list as |item|}}
    <tr>
      <td>{{item.ingredient.group}}</td>
      <td>{{item.ingredient.name}}</td>
      <td>{{item.weight}}g</td>
    </tr>
  {{/each}}
</table>

<br>

<button {{action "add"}}>Add</button>

<br>
<br>

{{total}}
import Ember from 'ember';

export default Ember.Controller.extend({
  appName: 'Ember Twiddle',
  list: [],
  unit: 'kcal',
  
  total: Ember.computed('list.[]','unit', function() {
    let total = 0;

    this.get('list').forEach(item => {
      let weight = item.weight;

      item.ingredient.nutrients.forEach(nutrient => {
        if (nutrient.name === this.get('unit')) {
          total += weight * nutrient.nutritionalValue;
        }
      });
    });
    return total;
  }),
  
  actions: {
  	add() {
  		this.get('list').pushObject({
      	ingredient: {
        	name: 'Potato',
          group: 'Veggies',
          nutrients: [{
          	name: 'kcal',
            nutritionalValue: 87
          }, {
          	name: 'kJ',
            nutritionalValue: 42
          }]
        },
        weight: 42
      })
		}
	}
});