Dan T
Dan T

Reputation: 35

How to push an object into an array using a form in Angular JS

I'm new to angular and having some trouble setting this up. How do you setup a form and controller to push a new object into an existing array?

index.html:

<html ng-app="gemApp">
<div ng-controller="storeController as store">
  <h3>Gems</h3>

  <div ng-repeat="item in store.products" | orderBy:"name">  
    <h5>{{item.name}}</h5>
    <h5>{{item.price | currency}}</h5>
  </div>
</div>

app.js:

var app = angular.module("gemApp", []);

app.controller("storeController", storeController)

function storeController(){
  this.products = gems;
}
var gems = [
  { name: 'Azurite', price: 2.95 },
  { name: 'Bloodstone', price: 5.95 },
  { name: 'Zircon', price: 3.95 }
];

Upvotes: 0

Views: 1362

Answers (1)

lealceldeiro
lealceldeiro

Reputation: 14958

This is a very basic sample of how you could do it. Bear in mind that I omitted validations, etc. and that the data stored here is just kept in memory. For storing this in time you have to save it to a database.

Snippet

var app = angular.module("gemApp", []);

app.controller("storeController", storeController)

function storeController() {
  var self = this;
  self.products = gems;
  self.current = {};

  this.add = function() {
    gems.unshift(angular.copy(self.current));
    self.current = {};
  }
}
var gems = [{
    name: 'Azurite',
    price: 2.95
  },
  {
    name: 'Bloodstone',
    price: 5.95
  },
  {
    name: 'Zircon',
    price: 3.95
  }
];
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<div ng-app="gemApp" ng-controller="storeController as store">
  
  <form>
  <label>Name</label>
    <input type="text" ng-model="store.current.name">
    <br>
    <label>Price</label>
    <input type="number" ng-model="store.current.price">
    <br>
    <input type="button" value="Guardar" ng-click="store.add()">
  </form>

<h3>Gems</h3>

  <div ng-repeat="item in store.products" | orderBy: "name">
    <h5>{{item.name}}</h5>
    <h5>{{item.price | currency}}</h5>
  </div>
</div>

Upvotes: 2

Related Questions