It turned out that the @luacassus answer about the track by option of the ng-repeat directive was very useful, but did not solve my problem. The track by function was to add new invoices coming from the server, but there was a problem clearing inactive invoices. So this is my solution to the problem:
function change(scope, newData) { if (!scope.invoices) { scope.invoices = []; jQuery.extend(true, scope.invoices, newData) } // Search and update from server invoices that are presented in scope.invoices for( var i = 0; i < scope.invoices.length; i++){ var isInvoiceFound = false; for( var j = 0; j < newData.length; j++) { if( scope.invoices[i] && scope.invoices[i].id && scope.invoices[i].id == newData[j].id ) { isInvoiceFound = true; jQuery.extend(true, scope.invoices[i], newData[j]) } } if( !isInvoiceFound ) scope.invoices.splice(i, 1); } // Search and add invoices that came form server, but are nor presented in scope.invoices for( var j = 0; j < newData.length; j++){ var isInvoiceFound = false; for( var i = 0; i < scope.invoices.length; i++) { if( scope.invoices[i] && scope.invoices[i].id && scope.invoices[i].id == newData[j].id ) { isInvoiceFound = true; } } if( !isInvoiceFound ) scope.invoices.push(newData[j]); } }
In my web application, I am using jQuery .extend() . There is a good alternative in the lo-dash library.
source share