假设我有 n 个元素。在 DOM 中使用 ng-repeat 渲染。
现在我有了上移和下移元素的功能。为此,我使用 jQuery 根据方向(向上或向下)交换两个元素。 效果很好。
但是在交换之后我失去了所 Angular 绑定(bind)。我想要原样的绑定(bind)。
Javascript
$scope.move = function(event, direction) {
var div1 = $(event.currentTarget).parent(),
div2 = direction === 'up' ? $(div1).prev() : $(div1).next(),
tdiv1 = div1.html(),
tdiv2 = div2.html();
div1.html(tdiv2);
div2.html(tdiv1);
}
HTML
<div ng-repeat="item in itemList">
{{$index}}
<div ng-click="move($event, 'up')"> Move up </div>
<div ng-click="move($event, 'down')"> Move Down </div>
</div>
如您所见,交换一次后,我无法再次交换它们。 我认为绑定(bind)必须丢失。
感谢任何帮助
最佳答案
像这样定义移动:
$scope.move = function(index, direction) {
var itemToMove = $scope.itemList[index];
if(direction==='up'){
$scope.itemList[index] = $scope.itemList[index - 1];
$scope.itemList[index - 1] = itemToMove;
} else{
$scope.itemList[index] = $scope.itemList[index + 1];
$scope.itemList[index + 1] = itemToMove;
}
if(!$scope.$$phase)
$scope.$apply();
};
与其传入 $event 来操作 DOM,不如传入 $index 来操作数组:
<div ng-repeat="item in itemList">
{{$index}}
<div ng-click="move($index, 'up')"> Move up </div>
<div ng-click="move($index, 'down')"> Move Down </div>
</div>
关于javascript - Angular js中的交换元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42981625/