我有一组具有嵌套数组的json对象。我正在使用ng-repeat来创建包含这些嵌套数组的列表。我想在按钮点击时动态删除列表中的项目。我在控制器中编写了一个函数来执行此操作 -
$scope.remove= function(path){
var obj = $scope.results[$scope.editIndex];
var i;
for(i = 0; i<path.length-1;i++){
var key = path[i].key;
var index = path[i].index;
if(!obj[key]) return;
obj = obj[key]
}
delete obj[path[i].key][path[i].index];
}
并将其称为 -
<ul ng-show="showFeatures">
<li ng-repeat="(featureIndex,feature) in result.features">
<span ng-bind="feature" contenteditable={{result.edit}}></span>
<i class="flr-always material-icons pointer" ng-show="result.edit" ng-click="remove([{key:'features',index:featureIndex}])">delete</i>
</li>
</ul>
问题是我不能删除多个元素,因为第一个元素索引会在数组中更改,但ng-repeat不会更改其范围内的索引。我怎么解决这个问题 ?我可以制作ng-repeat,在我做任何改变之后重新绘制自己。我只是在学习角度js,所以如果有更好的方法可以做这些事情,请指导我。
答案 0 :(得分:0)
<li ng-repeat="(featureIndex,feature) in result.features">
<span ng-bind="feature" contenteditable={{result.edit}}></span>
<i class="flr-always material-icons pointer" ng-show="result.edit" ng-click="remove([{key:'features',index:featureIndex}])">delete</i>
</li>
此处 result.features 是一个数组。因此,从AngularJS模板发送 $ index ,该模板将对应于您要删除的数组索引。
例如,ng-click =&#34;删除($ index)&#34;
然后在控制器
function remove(index){
$scope.result.features.splice($index, 1)
}
答案 1 :(得分:0)
试试这个:
<li ng-repeat="feature in result.features">
<span ng-bind="feature" contenteditable={{result.edit}}></span>
<i class="flr-always material-icons pointer" ng-show="result.edit" ng-click="remove(feature )">delete</i>
</li>
并删除功能
function remove(feature){
var index = $scope.result.features.indexOf(feature);
if(index > -1)
$scope.result.features.splice(index, 1);
}
var app = angular.module("app", []);
app.controller('mainCtrl', function($scope){
$scope.result = {
features:
[
"ali","reza","amir"
]
};
$scope.remove = function(feature){
var index = $scope.result.features.indexOf(feature);
if(index > -1)
$scope.result.features.splice(index, 1);
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet"/>
<div ng-app="app" ng-controller="mainCtrl">
<li ng-repeat="feature in result.features">
<span ng-bind="feature"></span>
<i ng-click="remove(feature)">delete</i>
</li>
</div>
&#13;