如何使用 ng-repeat $index 在数组中查找元素
How to use ng-repeat $index to find element in array
在我的 $scope 中,我有一个 属性,它是一个汽车数组,适当地命名为 $scope.cars
。用户可以删除汽车。我将汽车的 $index(由 ng-repeat 创建)作为参数传递给删除函数 deleteThis
,但是在我接收参数 $index
的 JavaScript 函数中,我不知道如何使用 ng-repeat 创建的索引找到要从 $scope.cars 中删除的汽车,因为 $index 不是 $scope.cars 的原生部分。请告诉我怎么做
$scope.deleteThis = function($event, $index){
// how can I use $index to find car in $scope.cars to delete
}
<div ng-repeat="car in cars">
<div class="row">
<div class="col-md-1"><h2>{{car.name}}</h2>{{car.make}}</div>
<div class="col-md-2"></div>
<span class="delete" ng-click="deleteThis($event, $index)">x</span>
</div>
不需要使用索引,直接传对象car
拼接出来即可
<span class="delete" ng-click="deleteThis(car)">x</span>
和
$scope.deleteThis = function(car){
var cars = $scope.cars;
cars.splice(cars.indexOf(car), 1);
}
你也可以使用 $index(但是当你有像 orderBy 这样的过滤器或任何其他过滤器结合 ng-repeat 表达式时,使用 $index 是很棘手的,$index 可能不是原始数组中的真正索引) . $index
未附加到重复对象,但附加到 ng-repeat
创建的子作用域。如果要在 ng-repeat 中重用部分视图,则传递 car
与使用 $index 相比更具可读性和明确性,并且更可重用。
如果你仍然使用索引,那么就这样做:
$scope.deleteThis = function(index){
$scope.cars.splice(index, 1);
}
在我的 $scope 中,我有一个 属性,它是一个汽车数组,适当地命名为 $scope.cars
。用户可以删除汽车。我将汽车的 $index(由 ng-repeat 创建)作为参数传递给删除函数 deleteThis
,但是在我接收参数 $index
的 JavaScript 函数中,我不知道如何使用 ng-repeat 创建的索引找到要从 $scope.cars 中删除的汽车,因为 $index 不是 $scope.cars 的原生部分。请告诉我怎么做
$scope.deleteThis = function($event, $index){
// how can I use $index to find car in $scope.cars to delete
}
<div ng-repeat="car in cars">
<div class="row">
<div class="col-md-1"><h2>{{car.name}}</h2>{{car.make}}</div>
<div class="col-md-2"></div>
<span class="delete" ng-click="deleteThis($event, $index)">x</span>
</div>
不需要使用索引,直接传对象car
拼接出来即可
<span class="delete" ng-click="deleteThis(car)">x</span>
和
$scope.deleteThis = function(car){
var cars = $scope.cars;
cars.splice(cars.indexOf(car), 1);
}
你也可以使用 $index(但是当你有像 orderBy 这样的过滤器或任何其他过滤器结合 ng-repeat 表达式时,使用 $index 是很棘手的,$index 可能不是原始数组中的真正索引) . $index
未附加到重复对象,但附加到 ng-repeat
创建的子作用域。如果要在 ng-repeat 中重用部分视图,则传递 car
与使用 $index 相比更具可读性和明确性,并且更可重用。
如果你仍然使用索引,那么就这样做:
$scope.deleteThis = function(index){
$scope.cars.splice(index, 1);
}