0

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.

1
  • You are pushing the same element i guess.. $scope.selectedFish.push(newFishToAdd[0]); use angular.copy for deep copying. Commented Oct 10, 2016 at 10:26

2 Answers 2

1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.