0

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 }
];
3
  • What's the behavior you're expecting? Add a new item from a form to your gems? Commented Mar 6, 2017 at 22:23
  • Yes, a simple form in my index.html that would enable me to push a new object into my gems array. Commented Mar 6, 2017 at 22:30
  • Have you tried anything? What's the concrete problem you're facing? Commented Mar 6, 2017 at 22:33

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.