Push product into an array model, controller

How could I push an item into an array in this case.

//controlle/product.js

import Controller from ‘@ember/controller’;

export default Controller.extend({
appName: “ShoppingCart”,

products: [],

action: {
        add() {
            this.get('products').pushObject(this.get('product'));
        }
    }

});

//template/product.js

I am Product

{{appName}}

{{#each model as | product|}}

{{product.title}}

{{product.owner}}

{{product.city}}

<button {{action 'add' product}}>Add</button>
{{/each}}
    {{#each products as |product index| }}
  • {{product}}(remove)
  • {{/each}}

{{outlet}}

//router/product.js import Ember from ‘ember’;

export default Ember.Route.extend({ model() { return [{

              id: 1,
              title: 'Grand Old Mansion',
              owner: 'Veruca Salt',
              city: 'San Francisco',  
        }, {
              id: 2,
              title: 'Grand Old Mansion',
              owner: 'Veruca Salt',
              city: 'San Francisco',  
        }, {
              id: 3,
              title: 'Grand Old Mansion',
              owner: 'Veruca Salt',
              city: 'San Francisco',  
        }, {
              id: 4,
              title: 'Grand Old Mansion',
              owner: 'Veruca Salt',
              city: 'San Francisco',  
        }];
  }

});

please do better code formatting. I believe you need to use product variable passed to add action, so it would be

export default Controller.extend({
  appName: “ShoppingCart”,
  products: [],
  action: {
    add(product) {
      this.get(‘products’).pushObject(product);
    }
  }
});
2 Likes

Forgot to add product as a parameter in add function, my bad

I also recommend not setting the value of products at the root level since this can lead to memory leaks especially in tests. Its been recommended to set its initial value in the init lifecycle method.

export default Controller.extend({
  appName: “ShoppingCart”, 
  products: null, 
  init() {
    this.set('products', []);
  },
  action: { 
    add(product) { 
      this.get('products').pushObject(product); 
    }
  }
});
recordlist.push(data)
    console.log(recordlist)
    self.set('recordlist',[])
      Ember.set(self.get('recordlist'),'data',recordlist)
    console.log(self.get('recordlist'))