[英]Dynamically change child element order in Angular ng-repeat
背景
我有一個角度表指令,用戶可以自定義列順序(通過拖放)。 數據行使用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
正在使用在運行時構造的編譯模板,但是如何使新列對象也保持新的列順序呢?
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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.