0

I have a question about the $scope values.

Example :

$scope.editItem = $scope.data.item;

So in $scope.editItem I have the same value as $scope.data.item.

But If I modify a value in $scope.editItem, the value is changing too in $scope.data.item.

I'm creating an edition form in a grid, and I'd like to edit items without changing the original value.

So if the user begin to edit the row, and cancel then I need to get back the original datas in my $scope.editITem object.

3 Answers 3

3

This happens because you're assigning a reference to $scope.data.item, not copying the value.

In order to achieve what you want, you need to deep copy your object using

$scope.editItem = angular.copy($scope.data.item)

Sign up to request clarification or add additional context in comments.

Comments

2

As long as I understand you only want to copy the value from one variable into another instead of the reference. A dummy way I know to accomplish that is to use angular.copy (doc) so that you can get this

$scope.editItem = angular.copy($scope.data.item)

Comments

1

It's happening because you are assigning reference to $scope.data.item. So as the reference/address is same for both scope variables, it's updating whenever you are updating $scope.editItem. (two-way binding concept)

So, all you have to do is, assign a copy of $scope.data.item to $scope.editItem. Then your problem'll be fixed.

Do as follow:

$scope.editItem = angular.copy($scope.data.item)

For more please read, https://docs.angularjs.org/api/ng/function/angular.copy

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.