ng-repeat shows terrible performance with large lists - angularjs

I'm experiencing performance issues when using ng-repeat for long lists (thousands of records) that need to be shown within a table.
Here is the HTML I'm using:
<table class="table table-hover">
<thead>
<tr>
<th ng-repeat="One_Header in Data_List.Header track by $index">{{One_Header}}</th>
</tr>
</thead>
<tbody>
<tr ng-model="Data_List" ng-repeat="One_Source in Data_List.Body track by $index" style="cursor:pointer">
<td ng-repeat="One_Data_Field in One_Source track by $index">{{One_Data_Field}}</td>
</tr>
</tbody>
</table>
The received JSON (takes about 1 second to get it from the server) contains the data as follows:
"Data":{
"Header":["Title_1","Title_2","Title_3"],
"Body":[
["Rec_1_Data_1","Rec_1_Data_2","Rec_1_Data_3"],
["Rec_2_Data_1","Rec_2_Data_2","Rec_2_Data_3"],
["Rec_3_Data_1","Rec_3_Data_2","Rec_3_Data_3"],
:
["Rec_n_Data_1","Rec_n_Data_2","Rec_n_Data_3"]
]
}
I also tried one-directional binding (i.e. {{::One_Data_Field}}) without any noticeable improvement.
As stated above, response arrives within a second and then it takes up to 10 seconds for the table to be built.

in order to improve the performance, you can use pagination directives created using angular js.
Angular-Paging
pagination
If you are using Angular material design then I would highly recommend using virtual repeat
virtual repeat

you can try this sample pagination implementation:
var pageSize = 15;
$scope.paginationLimit = function(pagesShown) {
return pageSize * pagesShown.count;
};
$scope.hasMoreItemsToShow = function(list, pagesShown) {
return pagesShown.count < (list.length / pageSize);
};
$scope.showMoreItems = function(pagesShown) {
pagesShown.count = pagesShown.count + 1;
};
<tr ng-model="Data_List" ng-repeat="One_Source in Data_List.Body track by $index " style="cursor:pointer">
<td ng-repeat="One_Data_Field in One_Source track by $index | limitTo: paginationLimit(pagesShown)">{{One_Data_Field}}</td>
</tr>
//sample row with show more button
<tr class="showMore">
<td></td>
<td class="showBtn">
<button type="button" class="btn btn-primary btn-lg" ng-init="pagesShown={'count': 1}" ng-click="showMoreItems(pagesShown)" ng-show="hasMoreItemsToShow(One_Source track, pagesShown)">Show More</button>
</td>
<td></td>
</tr>

Related

how to open row at the same index in ng-repeat , nested ng-repeat

I am new to angularjs and facing an issue with ng-repeat. A list of invoices repeated with ng-repeat, each invoice has List of Payments. I'm trying to get the payments on click of one of the repeated row and then another and so on.
when I open the first one it opens with exact data, when we open other row payments it opens with new payments by replacing the old one. Both payments of the First row payments and second row payments are same.
List of payments has to open with ng-repeat of that particular index. it has to happen for every invoice which is not happening with following
here is my html
<tbody data-ng-repeat="invoice in relatedInvoices>
<tr>
<td class="td-bottom-border">
{{invoice.PayableCurrencyCode}} {{invoice.PayablePaidAmount | number: 2}}<br />
<small>
<a data-ng-click="isOpenPayablePayments[$index] = !isOpenPayablePayments[$index]; togglePayablePayments(invoice.PayableInvoiceId)">Paid</a>
</small>
</td>
</tr>
<tr data-ng-show="isOpenPayablePayments[$index]">
<td>
<table>
<thead>
<tr>
<th>Transaction Id</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="payment in payablePayments">
<td>{{payment.TransactionId}}</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
Here is my javascript
var getPayments = function (invoiceId) {
paymentService.getPayments(invoiceId).then(function (paymentsResponse) {
return paymentsResponse.data;
});
};
$scope.togglePayablePayments = function(invoiceId) {
$scope.payablePayments = getPayments(invoiceId);
};
Every time on toggle click payments getting replaced with new payments. My problem is how to maintain the payments of particular index of every click and show at respective index. please help me out
Working Demo
<tbody>
<tr data-ng-repeat="city in name.cities">
<td>{{city.city}}</td>
</tr>
</tbody>
Actually you have to specifies main object name with the cities. name.cities
That's all !!!
Hope this will help you.
Feel free to ask any doubt on this.

Angular ng-repeat stay paged after filter

I'm using AngularJS and I have a simple table using ng-repeat and filter. When i insert anything at the search input it filters OK but it keeps paginated as it was before I filter the table. Any ideas why this is happening ?
Here's my code:
//some var initialization
$scope.pagina = {};
$scope.pagina.currentPage = 1,
$scope.pagina.numPerPage = 10,
$scope.pagina.maxSize = 5;
//return from server with data
coresFactory.getCores().then(function(response) {
$scope.tabelaCores = response.data;
$scope.filteredTodos = $scope.tabelaCores.cores.slice(0, 10);
});
//do pagination
$scope.$watch('pagina.currentPage', function() {
var begin = (($scope.pagina.currentPage - 1) * $scope.pagina.numPerPage),
end = begin + $scope.pagina.numPerPage;
$scope.filteredTodos = $scope.tabelaCores.cores.slice(begin, end);
},true);
<input ng-model="pesquisaTabela" type="search" style="width:300px;" class="form-control input-inline" placeholder="" aria-controls="sample_1"></label>
<table class="table" style="margin-bottom:5px;border:1px solid #DDDDDD" id="sample_1">
<thead>
<tr style="background-color:#F9F9F9">
<th style="width:100px; text-align:center;"> Id </th>
<th> Nome </th>
<th> Plural </th>
<th style="width:100px; text-align:center;"> Ativo </th>
</tr>
</thead>
<tbody>
<tr ng-repeat="cor in filteredTodos | filter:pesquisaTabela" ng-click="setSelected(cor.id)" ng-class="{linhaSelected: cor.id === idCorSelecionada}">
<td style="text-align:center;"> {{cor.id}} </td>
<td style="text-transform:capitalize"> {{cor.nome}} </td>
<td style="text-transform:capitalize"> {{cor.plural}} </td>
<td style="text-align:center;">
<span ng-if="cor.status=='sim'" class="label label-sm label-success"> Sim </span>
<span ng-if="cor.status=='nao'" class="label label-sm label-danger"> Não </span>
</td>
</tr>
</tbody>
</table>
<pagination first-text="<<" last-text=">>" next-text=">" previous-text="<" ng-model="pagina.currentPage" total-items="tabelaCores.cores.length" max-size="pagina.maxSize" boundary-links="true"></pagination>
You have quite a disconnect between various parts
Pagination is working off of one array, display from another and filter from yet another because when filter kicks in it returns a new filtered array.
The way you have things structured, your filter won't work properly either.
When you slice the main data array the filter is only going to work on that part that is sliced....not the whole main array
In order for pagination to be synchronized with filtering your simplest start point would likely be do your own filtering and share the same filtered array between the pagination and the table.
There are some other built in filters that you could use also like limitTo that takes 2 arguments limit and begin. That would help you get rid of currrent slice
There are lots of available grid/table directives available.
Using one of those would be my best suggestion
There is one other way you could do this all in the view. There is a syntax for ng-repeat that creates a new filtered array on the scope and therefore gives you access to it's length
<tr ng-repeat="row in filteredData = ( data |filter:pesquisaTabela | limitTo:10:start)">
Using this you could pass filteredData array to the total-items of the pagination directive.
It also now lets you do things like:
<div> Filtered length is: {{filteredData.length}}</div>

ng-init miscalculates aliased index after array.splice

I have encountered a strange behavior related to ng-init, any help would be appreciated.
I have a model object which has a flats property that is an array of flat objects. Each flat object has rooms property which is an array of room objects.
I'm trying to display flat and rooms as follows;
<table ng-repeat="flat in model.flats" ng-init="flatIndex = $index">
<thead>
<tr>
<td>{{flatIndex+1}}. {{flat.name}}</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="room in flat.rooms" ng-init="roomIndex = $index">
<td>{{roomIndex+1}}. {{room.name}}</td>
</tr>
</tbody>
</table>
If i delete a flat or room by using array.splice flatIndex and roomIndex variables doesn't seem to update properly even though $index and ui updates properly.
You can see the problem here in action.
Try to delete 1st, 2nd or 3rd flat or room object by clicking the delete link. Deleting last object from the array doesn't really expose the problem.
Any workarounds would also be appreciated.
This is a known behavior when you use ng-init, the scope property values set by ng-init are not watched and they don't update when you remove items from array to reflect the refreshed index position. So don't use ng-init, instead just use $index (deleteFlat($index)) and flat object reference (to get hold of rooms deleteRoom(flat,$index)).
<table ng-repeat="flat in model.flats track by flat.id">
<thead>
<tr>
<td colspan="2">{{$index+1}}. {{flat.name}}</td>
<td>DELETE FLAT</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="room in flat.rooms track by room.id">
<td> </td>
<td>{{$index+1}}. {{room.name}}</td>
<td>DELETE ROOM</td>
</tr>
</tbody>
</table>
and
$scope.deleteFlat = function(flatIndex){
$scope.model.flats.splice(flatIndex,1);
};
$scope.deleteRoom = function(flat,roomIndex){
flat.rooms.splice(roomIndex,1);
};
Plnkr
Or better off use the ids itself, deleteFlat(flat.id) and deleteRoom(room.id, flat).
<table ng-repeat="flat in model.flats track by flat.id">
<thead>
<tr>
<td colspan="2">{{$index + 1}}. {{flat.name}}</td>
<td>DELETE FLAT</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="room in flat.rooms track by room.id">
<td> </td>
<td>{{$index+1}}. {{room.name}}</td>
<td>DELETE ROOM</td>
</tr>
</tbody>
</table>
and
$scope.deleteFlat = function(flatId){
$scope.model.flats.splice(_getItemIndex(flatId, $scope.model.flats), 1);
};
$scope.deleteRoom = function(roomId, flat){
flat.rooms.splice(_getItemIndex(roomId, flat.rooms), 1);
};
function _getItemIndex(imtId, itms){
var id ;
itms.some(function(itm, idx){
return (itm.id === imtId) && (id = idx)
});
return id;
}
Plnkr2

ngRepeat with Table: Change a cell's display text

I have a list of mails which I want to show in a grid (<table>). Some of these mails have attachments. For their corresponding rows, I would like to show an attachment icon in the attachment column. For rest, it should be empty.
JsFiddle: http://jsfiddle.net/6s4Z5/
My template is as follows:
<table id="resultTable">
<thead>
<tr>
<th ng-repeat="columnId in schema.columnOrder">
<img src="icon_attach.png" ng-if="columnId == 'hasAttachments'">
{{schema.columns[columnId].displayText}}
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in results.mails">
<td ng-repeat="columnId in schema.columnOrder">
<img src="icon_attach.png" ng-if="columnId == 'hasAttachments' && row.hasAttachments">
<span ng-if="columnId != 'hasAttachments'" >{{ row[columnId] }}</span>
</td>
</tr>
</tbody>
</table>
where schema.columnOrder is an array of columnIds to be shown in the table.
This template is working but is this the best way to implement this? Moreover, I have to add an extra <span> for ng-if statement. Can that also be removed?
You pretty much can change it to something like:
<span ng-if='your check'><img src=''/>{{row[columnId}}</span>
You could set (in the controller) the value of the column hasAttachments to be the image you want to display there.

angularJS - Repeating tr's in a table, but dynamically adding more rows while looping

Since examples always tell more then just words here is what I would like to do in another language
<tr>
<c:forEach items="${items}" var="item">
<td>...</td>
<td>...</td>
<td>...</td>
<c:if test="${item.showWarning}">
</tr><tr><td colspan="3">${item.warning}</td>
</c:if>
</tr>
So this will loop over a set of items and show some properties of these items. If there is a warning, a new row will be added underneath the current row in which the warning will be shown. However, how can I do this in angularJs? If I put a ng-repeat on the tr, it will stop at the first end tag of tr. I have read on some other threads that this is not very easily done, but how can it be done? And yes, I really do want to use a table. Here is my contrived example with angularjs which is obviously not working as I would like it to. Any pointers how this can be done?
JSBin example with tr-ng-repeat
Currently (1.0.7/1.1.5) you can't output data outside the ng-repeat, but version 1.2(see youtube video AngularJS 1.2 and Beyond at 17:30) will bring the following syntax(adapted to your example):
<tr ng-repeat-start="item in items">
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
<tr ng-repeat-end ng-show="item.showWarning">
<td colspan="3">{{item.warning}}</td>
</tr>
The idea is that whatever is between -start and -end will be repeated including the -end element.
One solution that I can think of is having multiple tbody tags within the same table. Here is a discussion on the use of multiple tbody tags within the same table.
So, for your issue, you could have the following setup:
<table ng-controller="ItemController">
<thead>
<th>Name</th>
<th>Description</th>
<th>warning?</th>
</thead>
<tbody ng-repeat="item in items">
<tr>
<td>{{item.name}}</td>
<td>{{item.description}}</td>
<td>{{item.warning}}</td>
</tr>
<tr ng-show="item.warning">
<td colspan="3" style="text-align: center">Warning !!!</td>
</tr>
</tbody>
</table>
Repeat the table body as many times as there are entries for the table and within it have two rows - one to actually display the row entry and one to be displayed conditionally.
You can repeat over the tbody
<tbody ng-repeat="item in items">
<tr>
<td>{{item.name}}</td>
<td>{{item.description}}</td>
<td>{{item.warning}}</td>
</tr>
<tr ng-show="item.warning">
<td colspan="3">Warning !!!</td>
</tr>
</tbody>
Also you do not need to wrap the ng-show expression in {{}}, you can just use item.warning

Resources