繁体   English   中英

数组拼接删除了AngularJS中的错误元素

[英]Array splice removes the wrong element in AngularJS

我阅读了其他人的所有其他问题和答案,但仍然无法解决。

HTML:

<table class="table table-striped" ng-show="coffees.length>0">
                <thead>
                  <tr>
                    <th>Drink</th>
                    <th>Price</th>
                    <th>Number per week</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  <tr ng-repeat="c in coffees">
                    <td>{{c.type}}</td>
                    <td>{{c.price | currency:"&pound;"}}</td>
                    <td>{{c.numberpw}}</td>
                    <td><a href ng-click="removeCoffee($index)">X</a></td>
                  </tr>
                </tbody>
              </table>

app.js:

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

app.controller('pageController',function($scope){       
    $scope.coffees=[];  
});

app.controller('coffeeController',function($scope){     

    $scope.addCoffee=function(coffee){      
        $scope.coffees.push(coffee);
        $scope.coffee={};
    }

    $scope.removeCoffee=function(el){       
        $scope.coffees.splice($scope.coffees[el],1);
    }
});

coffeeController嵌套在pageController中,因此我可以访问coffeeController内部的$ scope.coffees。 并且addCoffee函数接受一个看起来像这样的对象:

<select name="CoffeeType" ng-model="coffee.type" ng-options="type for type in 
['Espresso','Latte']" class="form-control" required>
<option value="">Please select</option>
</select>                      

<input type="text" placeholder="&pound;00.00" ng-pattern="/^0|[1-9][0-9]*$/" ng-model="coffee.price" name="CoffeePrice" class="form-control" required />

<select name="NumberPerWeek" class="form-control" ng-model="coffee.numberpw" ng-options="n for n in [1,2,3,4,5]" required>
<option value="">Please select</option>
</select>

<input type="submit" class="btn btn-primary pull-left" value="Add Drink" ng-click="addCoffee(coffee)" />

它完美地添加了对象,但是每次都删除了错误的对象。

splice期望开始/计数整数。 $scope.coffees[el]是一个对象,但是您要将$index传递给该方法。 更新您的删除方法,如下所示:

$scope.removeCoffee=function(el){       
    $scope.coffees.splice(el,1);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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