2016-09-23 142 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