0
我試圖在我的AngularJS應用程序中使用此代碼https://stackoverflow.com/a/20096401/2542165作爲指令。此代碼合併包含相同值的連續單元格(使用rowspan)。AngularJS:未綁定到指令中的值
我的表格是用ng-repeat生成的,而我的問題是,在我的指令中,比較值是"{{item.value1}}"
和"{{item.value2}}"
而不是真實值。
在下面的例子中,最後兩行被合併,但不應該。
var app = angular.module('plunker', []);
app.controller('DemoController', function ($scope) {
\t $scope.items =
\t [
\t {
\t \t "value1":"value1",
\t \t "value2":"value2",
\t },
\t {
\t \t "value1":"value1",
\t \t "value2":"value4",
\t }
\t ]
});
app.directive('mergeTable', [function() {
\t return {
\t \t restrict: 'A',
\t \t link: function(scope, element, attrs) {
\t \t \t
\t \t \t function merge() {
\t \t \t \t var mergeTableColIndex = attrs.mergeTableColIndex;
\t \t \t \t var table = element;
\t \t \t \t var rows = table.find($("tr"));
\t \t \t \t var colsLength = $(rows[0]).find($("td")).length;
\t \t \t \t var removeLater = [];
\t \t \t \t for (var i = 0; i < colsLength; i++) {
\t \t \t \t \t if(mergeTableColIndex.indexOf(i) !== -1) {
\t \t \t \t \t \t var startIndex = 0;
\t \t \t \t \t \t var lastIndex = 0;
\t \t \t \t \t \t var startText = $($(rows[0]).find("td")[i]).text();
\t \t \t \t \t \t for (var j = 1; j < rows.length; j++) {
\t \t \t \t \t \t \t var cRow = $(rows[j]);
\t \t \t \t \t \t \t var cCol = $(cRow.find("td")[i]);
\t \t \t \t \t \t \t var currentText = cCol.text();
\t \t \t \t \t \t \t if (currentText == startText) {
\t \t \t \t \t \t \t \t removeLater.push(cCol);
\t \t \t \t \t \t \t \t lastIndex = j;
\t \t \t \t \t \t \t } else {
\t \t \t \t \t \t \t \t var spanLength = lastIndex - startIndex;
\t \t \t \t \t \t \t \t if (spanLength >= 1) {
\t \t \t \t \t \t \t \t \t $($(rows[startIndex]).find("td")[i]).attr("rowspan", spanLength + 1);
\t \t \t \t \t \t \t \t }
\t \t \t \t \t \t \t \t lastIndex = j;
\t \t \t \t \t \t \t \t startIndex = j;
\t \t \t \t \t \t \t \t startText = currentText;
\t \t \t \t \t \t \t }
\t
\t \t \t \t \t \t }
\t \t \t \t \t \t spanLength = lastIndex - startIndex;
\t \t \t \t \t \t if (spanLength >= 1) {
\t \t \t \t \t \t \t $($(rows[startIndex]).find("td")[i]).attr("rowspan",
\t \t \t \t \t \t \t \t \t spanLength + 1);
\t \t \t \t \t \t }
\t \t \t \t \t }
\t \t \t \t }
\t \t \t \t
\t \t \t \t for(i in removeLater){
\t \t \t \t \t $(removeLater[i]).remove();
\t \t \t \t }
\t \t \t }
\t \t \t
\t \t \t scope.$watch(attrs.mergeTable, function(value) {
\t \t \t \t merge();
\t \t \t });
\t \t }
\t };
}]);
<!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>