javascript - Angular js中的交换元素

标签 javascript jquery angularjs

假设我有 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/

相关文章:

javascript - no-use-before-define 在扩展 eslint-config-react-app 时不起作用

Javascript 测验 - 如何计算多个选择元素中答案的分数?

javascript - 我需要一个技巧来模拟标签上的插入符号

node.js - AngularJS 教程步骤_02 的问题

javascript - 编辑时更新输入的绑定(bind)值

javascript - 使用 .animate( {'height' :'toggle' }) 时出现奇怪的 IE8 问题

php - 使用ajax插入MySql数据库

javascript - 使用 Angular 映射 JSON 数据模型

javascript - C3 中带有 JSON 数据的多个 Y 轴

jquery - 如何创建一个类似于stackoverflow的框,点击关闭