我試圖在表中顯示一個大的數據集。顯示一個大表「角度的方式」
首先,我只是用嵌套NG-重複:
<table>
<tr ng-repeat="row in rows">
<td>{{row.meta}}</td>
<td ng-repeat="cell in row.cells">{{cell.data}}</td>
<tr>
</table>
(該代碼是我的意思的例子,它實際上並不符合我的數據集下面的代碼呢。)
此代碼非常乾淨,但很容易需要幾秒鐘才能渲染。數據集非常大(數千個單元格適合屏幕)。
我把它改寫了這個怪物:
angular.module('systeem3').directive('dayStatusTable', function(){
return{
restrict: 'E',
scope: {
housestatus: '='
},
link: function(scope, elem, attr) {
// Doing this manually since the Angular way is slooow....
scope.$watch('housestatus', function(newValue) {
if (newValue && Array.isArray(newValue)) {
var stringparts = ['<table>'];
for (houseline of newValue) {
stringparts.push('<tr><td>'+houseline.houseName+'</td>');
for (day of houseline.daystatus) {
var date = day.date.split('-')[2];
var weekday = day.date.split('-')[3];
var weekendOrWeekday = (weekday == 0 || weekday == 6) ? 'weekend' : 'weekday';
stringparts.push('<td class="',
day.status, ' ',weekendOrWeekday,
'">',
date,
'</td>');
}
stringparts.push('</tr>');
}
stringparts.push('</table>');
elem.html(stringparts.join(''));
}
});
},
}
});
結果是驚人的:它採取幾秒鐘去渲染小於50ms,其中大部分是由elem.html()
呼叫吸收。
但是,代碼看起來很糟糕,而且非常不合適。我該如何改進?
國際海事組織,這應該張貼在'codereview.stackexchange.com' – naveen
也許。我猶豫不決把它放在那裏或這裏。它會適合那裏,因爲我問關於imporving我的代碼,但它適合在這裏,因爲我也問如何呈現一個大角度一般的大型表。 – user1582024
你發佈的兩個解決方案是非常不同的。使用'ng-repeat',Angular爲每行和單元格創建一個範圍對象,並設置觀察者爲您提供數據綁定。您的自定義指令只是生成靜態HTML。但是你的指令不是「無角度的」 - 你仍然使用自定義指令在框架內工作。 – user1620220