我正在尝试在我的AngularJS应用程序中使用此代码https://stackoverflow.com/a/20096401/2542165作为指令。此代码合并包含相同值(带有rowspan)的连续单元格。
我的表是使用ng-repeat生成的,我的问题是,在我的指令中,比较值是"{{item.value1}}"
和"{{item.value2}}"
而不是实际值。
在下面的示例中,最后两行是合并的,但不应该合并。
var app = angular.module('plunker', []);
app.controller('DemoController', function ($scope) {
$scope.items =
[
{
"value1":"value1",
"value2":"value2",
},
{
"value1":"value1",
"value2":"value4",
}
]
});
app.directive('mergeTable', [function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
function merge() {
var mergeTableColIndex = attrs.mergeTableColIndex;
var table = element;
var rows = table.find($("tr"));
var colsLength = $(rows[0]).find($("td")).length;
var removeLater = [];
for (var i = 0; i < colsLength; i++) {
if(mergeTableColIndex.indexOf(i) !== -1) {
var startIndex = 0;
var lastIndex = 0;
var startText = $($(rows[0]).find("td")[i]).text();
for (var j = 1; j < rows.length; j++) {
var cRow = $(rows[j]);
var cCol = $(cRow.find("td")[i]);
var currentText = cCol.text();
if (currentText == startText) {
removeLater.push(cCol);
lastIndex = j;
} else {
var spanLength = lastIndex - startIndex;
if (spanLength >= 1) {
$($(rows[startIndex]).find("td")[i]).attr("rowspan", spanLength + 1);
}
lastIndex = j;
startIndex = j;
startText = currentText;
}
}
spanLength = lastIndex - startIndex;
if (spanLength >= 1) {
$($(rows[startIndex]).find("td")[i]).attr("rowspan",
spanLength + 1);
}
}
}
for(i in removeLater){
$(removeLater[i]).remove();
}
}
scope.$watch(attrs.mergeTable, function(value) {
merge();
});
}
};
}]);
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="DemoController">
<table border="1" merge-table-col-index='[0,1,2]' merge-table='items'>
<tr>
<td>a</td>
<td>b</td>
</tr>
<tr>
<td>a</td>
<td>c</td>
</tr>
<tr ng-repeat='item in items'>
<td>{{item.value1}}</td>
<td>{{item.value2}}</td>
</tr>
</table>
</div>
</body>
</html>
答案 0 :(得分:0)
解决方法是在调用merge()之前等待angular渲染,使用$ evalAsync:
scope.$watch(attrs.mergeTable, function(value) {
scope.$evalAsync(function() {
merge();
});
});