简体   繁体   中英

How do I push multiple objects to an array without overwriting the array with the most recent object that was pushed

The problem i'm having is that whenever I click submit, the object gets pushed to the array. When I click submit to add another ingredient to the array it pushes another object to the array but also copies it's information into all previous objects in the array.

html

<form ng-submit="addToIngredients(newIngredient)">
        <input ng-model="newIngredient.quantity" placeholder="e.g. 1/3" type="text">
        <select ng-model="newIngredient.unit">
          <option value="ml">ml</option>
          <option value="l">l</option>
          <option value="tsp">tsp</option>
          <option value="tbsp">tbsp</option>
          <option value="floz">floz</option>
          <option value="cup">cup</option>
          <option value="pnt">pnt</option>
          <option value="qt">qt</option>
          <option value="gal">gal</option>
          <option value="qty">qty</option>
        </select>
        <select ng-options="stockItem.name for stockItem in stockItems track by stockItem._id"
                ng-model="newIngredient.item">
        </select>
        <button type='submit'>Add to ingredients</button>
      </form>

function on controller

$scope.ingredients = [];
$scope.addToIngredients = function(newIngredient){
    $scope.ingredients.push(newIngredient);
  }

This is probably javascript inheritance.

You could try:

$scope.ingredients.push(angular.copy(newIngredient));

It is a hack...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM