2016-09-23 144 views
1

背景在角NG-重复

我具有有角表指示其中用户可以(通过拖放)自定义列顺序动态更改子元件顺序。数据行使用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

听起来像是你需要一个嵌套的NG-重复,其中列在自己的对象,基于作用域(每行)进行修改。 – isherwood

+2

你面临的问题是因为你在混合使用jQuery DOM操作和AngularJS。理想情况下,而不是通过jQuery更改DOM,为什么不尝试以编程方式更改数据? – nikjohn

+0

我有一个想法 - 将使用'行'子指令''观看'列顺序数组并设置列顺序类。将发布我的答案。 – remarsh

回答

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] 
+0

感谢您的努力,但此解决方案无法扩展,因为用户可以移动任何列。 – remarsh