我有一个使用 ng-repeat 显示并按名称 desc 排序的列表。
每个项目都有一个item-delete
指令,它包含和在项目单击时我使用给定的函数$index
从列表中删除项目,然后我更新列表 - 这不起作用!index
splice
从我的调试结果来看,orderBy
在指令内部调用过滤器后会出现问题。如果我像这样直接删除项目,scope.list.splice(index, 1)
它可以工作,但删除的项目不是正确的项目,因为项目是由 ng-repeat 订购的,所以我必须以相同的方式订购它们,然后我可以执行正确的删除。
一种解决方法是$emit
新列表并更新控制器内的范围,但我不想这样做。测试和工作(见片段)。
Ascope.$apply
将遇到digest already in progress
错误(因为这部分代码在我的应用程序的承诺中)并且没有$timeout
列表在工作时不会更新(使用noFilter
例如,使用过滤器)。
*我正在使用指令从列表中删除一个项目,因为我在项目点击(DOM 更改、服务调用)上做了很多事情,而控制器不是这样做的地方(如果你在想为什么我'不是通过控制器执行此操作)。
另外,这里有一个 plnkr 。
// JS
var APP = angular.module('APP', []);
APP.controller('Home', function($scope, $filter){
var objData = {
"1": { id: 1, name: "Abc" },
"2": { id: 2, name: "Bbc" },
"3": { id: 3, name: "Fea" },
"4": { id: 4, name: "Dbc" }
};
$scope.list = $filter('objToArr')(objData);
//part of workaround...
$scope.$on('listUpdate', function(evt, data){
$scope.list = data;
})
});
APP.directive('itemDelete', function($filter, $timeout){
return{
restrict: 'A',
link: function(scope, el, attrs){
var delIndex;
attrs.$observe('itemDelete', function(val){
delIndex = val;
});
angular.element(el).click(function(){
console.log('deleting item index '+ delIndex);
console.log('list length before ' + scope.list.length);
//delete item from ng-repeat ordered list
$timeout(function(){
var listOrdered = $filter('orderBy')(scope.list, '-name'); //replace 'orderBy' with 'noFilter' -> it works, but removes wrong item!
//var listOrdered = scope.list; // uncomment & comment line before this -> it works, but removes wrong item!
listOrdered.splice(delIndex,1);
scope.list = listOrdered;
//workaround...
//scope.$emit('listUpdate', scope.list);
console.log('list length after ' + scope.list.length);
});
});
}
}
})
APP.filter('objToArr', function(){
return function(input){
var arrData = [];
angular.forEach(input, function(arr, key){
arrData.push(arr);
});
return arrData;
}
});
APP.filter('noFilter', function(){
return function(input){
return input;
}
});
ul li{ display: block; margin-bottom: 4px; background-color: #ccc; padding: 5px; }
ul{ list-style:none; }
<!DOCTYPE html>
<html ng-app="APP">
<head>
<script data-require="jquery@2.1.3" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://code.angularjs.org/1.3.15/angular.js" data-semver="1.3.15" data-require="angular.js@1.3.15"></script>
</head>
<body ng-controller="Home">
<h4>Click on item - remove from list</h4>
<ul>
<li item-delete="{{ $index }}" ng-repeat="item in list | orderBy:'-name'">{{ item.name }}</li>
</ul>
</body>
</html>