简体   繁体   中英

“track by $index” creating duplicates on save using ng-repeat

I'm having a problem when I update my object, it's creating a duplicate of this instance (singleOrder) in the model, instead of updating the exisiting one. I can't clear the whole $scope and reload, as I'm only updating part of the object.

Here's my save function:

$scope.saveDetails = function(singleOrder, data, status) {              

    OrdersService.updateOrders(singleOrder.order)

    .success(function(data, status) {
        angular.extend(singleOrder, data);                      
    })                             
}

Where singleOrder relates to an instance of my main OrderDetails object, used in ng-repeat

<div ng-repeat="singleOrder in orderDetails track by $index">

Here's the function called in my OrdersService, if that helps:

getData.updateOrders = function(data){
    var url = '/service/rest/orders';

    return $http.post(url, data)                    
};

Thanks for any help you can offer.



UPDATE: I've tried messing around with the track by and received the following results:

<div ng-repeat="singleOrder in orderDetails track by $index"> Saves the content fine, but creates a duplicate order on dom.

<div ng-repeat="singleOrder in orderDetails track by singleOrder.order.id"> This works as each order has a unique id. I can save fine and it doesn't create a duplicate in the dom, but I get a Duplicates in a repeater are not allowed in the console.

Confused as to why this is happening. Any ideas welcome!

angular.extend() returns the destination object, so maybe you could do something like this

OrdersService.updateOrders(singleOrder.order)
.success(function(data, status) {
    singleOrder = angular.extend(singleOrder, data);                      
})

But in my opinion it is better when server returns the whole object that the client needs. The code will be easier.

Just to follow up on this, it appears the issue wasn't with Angular, it was the data in the object. I can't say exactly what part was the problem, but after the content was updated, this started working with track by $index .

Thanks everyone for trying to help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM