ng-click中的$ index在firefox中不在chrome中

时间:2015-08-05 18:10:32

标签: javascript angularjs google-chrome firefox angularjs-ng-repeat

我在视图中有以下内容

 <tr ng-repeat="item in cart.getItems() track by $index" class="cart-item">
        <td>{{item.title}}</td>
        <td>{{item.quantity}}</td>
        <td><price value="item.price"></td>
        <td><button ng-click="remove(cart.getItems(), $index)">remove</button></td>
 </tr>

其中remove()函数定义如下:

$scope.remove = function(array, index){
    array.splice(index, 1);
    }

有趣的是,它在firefox 31.8.0中运行良好,但在谷歌Chrome 44.0.2403.89 beta(64位)中没有效果,点击remove按钮不会删除项目。问题是什么?

2 个答案:

答案 0 :(得分:2)

首先,不要在ng-repeat中使用方法。将数据分配给某个范围模型,例如$scope.cartItems并重复它。

其次,在remove方法中,仅传递当前项:<button ng-click="remove(item)">

第三,在控制器中:

$scope.remove = function(item){
    var index = $scope.cartItems.indexOf(item);
    $scope.cartItems.splice(index, 1);
}

答案 1 :(得分:0)

$scope.$apply()迫使重新绑定后,可能需要array.splice()

或者,不要在视图中两次调用.getItems()并将其传回控制器,只需在控制器范围内设置数组并在视图中引用它,也可以在删除方法中引用它。

所以在你的控制器中:

$scope.cartItems = cart.getItems();

然后你的观点是:

 <tr ng-repeat="item in cartItems track by $index" class="cart-item">
        <td>{{item.title}}</td>
        <td>{{item.quantity}}</td>
        <td><price value="item.price"></td>
        <td><button ng-click="remove($index)">remove</button></td>
 </tr>

和你的删除方法:

$scope.remove = function(index){
    $scope.cartItems.splice(index, 1);
    }

然后你在角度

内很好地保留了所有引用