表格是数据绑定到ng-repeat中的ng-model ...但是所有重复的值都被更改了?

时间:2015-11-28 19:08:07

标签: arrays angularjs angularjs-scope angularjs-ng-repeat angular-ngmodel

我正在制作一个简单的网络应用程序,允许用户选择食品并定制他们的订单(饮料,面和浇头)。我采取的方法是每个食品具有以下属性:

var food = {
 id:0,
 name:"Burger",
 drinks: [],
 sides: [],
 toppings: []
}

我正在拿整个饮料[obj1,obj2 ..]并将它们复制到我控制器范围内的新变量中。然后修改它们的数量属性。在表单提交后,带有新饮料阵列的食物对象将被保存到ShoppingCart工厂内的另一个阵列(购物车)中。是的,这确实意味着食物对象会收到饮料数量= 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
    };
}]);

这一切都有效,直到我尝试将另一个食品添加到购物车中。更改任何食品的饮料数量将改变所有其他食品的数量(在购物车内)。我怀疑这是由于我使用ng-repeat和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>

我的逻辑一定有问题。我知道复制整个饮料阵列是过分的,可以做得更好,但在我解决之前,我想弄清楚我当前的代码有什么问题。我再次从头开始,但碰到了同样的问题。谁能帮我?? :)

1 个答案:

答案 0 :(得分:1)

实际上$scope.drinks = $scope.all_drinks.slice();并没有复制整个饮料数组,只是将引用传递给另一个变量。两个变量都指向同一个数组。而不是这条线只需使用

angular.copy( $scope.all_drinks, $scope.drinks); // copies array into $scope variable which is connected to ng-repeat and ng-model