I am making a simple web app that allows users to select food items and customize their order (drink, sides and toppings). The approach I am taking is for each food item to have the following attributes:
var food = {
id:0,
name:"Burger",
drinks: [],
sides: [],
toppings: []
}
I am taking the entire array of drinks [obj1, obj2..] and copying them into a new variable inside the scope of my controller.. then modifying their quantity attribute. Upon form submit, the food object with its new drink array will be saved into another array (cart) inside the ShoppingCart factory. Yes this does mean that the food object will receive a drinks array with some drinks of quantity = 0.
angular.module('webMenu')
.controller('foodCtrl', ['$scope', 'SideFoods', 'ShoppingCart', 'FoodOrder', function($scope, SideFoods, ShoppingCart, FoodOrder){
$scope.food = FoodOrder.get();
$scope.all_drinks = SideFoods.get_drinks(); //grabs all drinks from drinks factory
$scope.drinks = $scope.all_drinks.slice(); // copies array into $scope variable which is connected to ng-repeat and ng-model
$scope.submitOrder = function(){ // copies the modified drinks to food.drinks
$scope.food.drinks = $scope.drinks;
ShoppingCart.add($scope.food); // shopping cart receives food
};
}]);
This all works until I try to add another food item into my shopping cart. Changing the drink quantities of any food item will change the quantities for all others (inside the shopping cart). I suspect it is due to the way I have been using ng-repeat and ng-model.
<div id='drinks' ng-repeat='drink in drinks track by $index'>
<div class='drink'>
<!-- Using ng-model on drink.quantity fails to use a unique array -->
<input type='number' ng-model='drink.quantity'>{{drink.name}} x{{drink.quantity}}
</div>
</div>
There must be something wrong with my logic here. I know that copying the entire drinks array is excessive and can be done better, but before I tackle that I want to figure out what's wrong with my current code. I started from scratch again but bumped into the same problem. Can anyone help me?? :)
Actually $scope.drinks = $scope.all_drinks.slice();
is not copying the entire drinks array, it is just passing reference to another variable. Both variables are pointing to same array. Instead of this line just use
angular.copy( $scope.all_drinks, $scope.drinks); // copies array into $scope variable which is connected to ng-repeat and ng-model