动态更改Angular ng-repeat中的子元素顺序

时间:2016-09-23 17:01:17

标签: javascript angularjs

背景

我有一个角度表指令,用户可以自定义列顺序(通过拖放)。数据行使用ng-repeat指令。

<table columno>
    <tr>
        <th>Column Head 1</th>
        <th>Column Head 2</th>
        <th>Column Head 3</th>
    </tr>
    <tr ng-repeat="item in items">
        <td>Column 1</td>
        <td>Column 2</td>
        <td>Column 3</td>
    </tr>
</table>

使用按钮简化小提琴而不是拖放@ https://jsfiddle.net/jn1y44s6/5/

问题:

当用户移动说第1列成为第2列时,移动正常。问题是当新对象添加到items数组时,新列将保持原始未更改的顺序。

我理解ng-repeat正在使用在运行时构造的编译模板,但是如何才能使新列的新列顺序保持不变?

1 个答案:

答案 0 :(得分:0)

Html代码

<div ng-app="fiddle" columnly>
   <button ng-click="addRow()">Add Row</button>
   <button ng-click="move()">Move Column 1</button>
   <table>
      <tr class="row">
         <th class="column move">Row 0 Head 1</th>
         <th class="column">Row 0 Head 2</th>
         <th class="column">Row 0 Head 3</th>
      </tr>
      <tr class="row" ng-repeat="item in items">
         <td class="column first move">Row {{item}} Column 1</td>
         <td class="column second">Row {{item}} Column 2</td>
         <td class="column">Row {{item}} Column 3</td>
      </tr>
   </table>
</div>

Controller.js

var app = angular.module('fiddle', []);
app.directive('columnly', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attr, $scope) {
            var count = 6;
            scope.items = [1, 2, 3, 4, 5];
            scope.firstClick = true;
            scope.addRow = function() {
                scope.items.push(count++);
                if ($("tr th:nth-child(2)").hasClass('move')) {
                    setTimeout(function() {
                        var abc = $("tr:nth-child(" + count + ")").children().eq(0).html();
                        var def = $("tr:nth-child(" + count + ")").children().eq(1).html()
                        $("tr:nth-child(" + count + ")").children().eq(1).html(abc);
                        $("tr:nth-child(" + count + ")").children().eq(0).html(def);
                        $("tr:nth-child(" + count + ")").children().eq(1).addClass('move')
                        $("tr:nth-child(" + count + ")").children().eq(0).removeClass('move')
                    });
                }
            };
            scope.move = function() {
                jQuery.each($("table tr"), function() {
                    $(this).children().eq(1).after($(this).children().eq(0));
                });
            };
        }
    }
});

小提琴链接

[https://jsfiddle.net/Anvesh2727/jn1y44s6/10/][1]