gilesrpa
gilesrpa

Reputation: 1061

AngularJS adding object to array updates all similar objects

I am getting data from a WebAPI and storing it in a scoped variable array products.

$scope.products

I also have a second scoped array

$scope.selectedFish = [];

What I am trying to do is find a product in the products array, modify it and add it into the selectedProducts array.

I have the following function declared on the same controller.

// Function to add a new fish to the selectedFish array
            $scope.add = function() {
                // Find existing fish from products list
                var newFishToAdd = $filter('filter') ($scope.products, { Id: $scope.selectedProduct });
                // Change the name property
                newFishToAdd[0].FishName = $scope.selectProductName;
                // Add new fish to the selected fish array
                $scope.selectedFish.push(newFishToAdd[0]);
                $scope.bindModel();
            }

This does work, but I am having difficulty where if I add the same product twice with different FishName values, it updates all entries in the array for the same selectedProduct with the last FishName entered.

Upvotes: 0

Views: 57

Answers (2)

TechnoTech
TechnoTech

Reputation: 799

You should try using angular.copy for this purpose. As it says in angular documentation (https://docs.angularjs.org/api/ng/function/angular.copy)

angular.copy

Creates a deep copy of source, which should be an object or an array.

If no destination is supplied, a copy of the object or array is created.

If a destination is provided, all of its elements (for arrays) or properties (for objects) are deleted and then all elements/properties from the source are copied to it.

If source is not an objector array(inc. nulland undefned), source is returned. If source is identical to destination an exception will be thrown.

Upvotes: 0

ram1993
ram1993

Reputation: 971

Its happening as object reference is same. use angular.copy().

$scope.add = function() {
    // Find existing fish from products list
    var newFishToAdd = $filter('filter')($scope.products, { Id: $scope.selectedProduct });

    var obj = angular.copy(newFishToAdd[0]);
    obj.FishName = $scope.selectProductName;

    // Add new fish to the selected fish array
    $scope.selectedFish.push(obj);
    $scope.bindModel();
}

Upvotes: 1

Related Questions