0

How can i prevent binding in this case:

$scope.data = [{i:0, a:0}, {i:0, a:0}, {i:0, a:0}];
$scope.twoofthedata = [$scope.data, $scope.data];

so that $scope.twoofthedata[0] is indipendent from $scope.twoofthedata[1]

plunker

1 Answer 1

3

In JavaScript, objects are manipulated by reference. This is not an Angular binding issue.

However Angular enables you to bypass this language constraint via the angular.copy method, which creates a deep copy of a given object.

$scope.data = [{i:0, a:0}, {i:0, a:0}, {i:0, a:0}];

// Manually call `angular.copy` on each member
$scope.twoofthedata = [
  angular.copy($scope.data),
  angular.copy($scope.data)
];

// Cleaner version (using `Array.prototype.map`)
$scope.twoofthedata = [$scope.data, $scope.data].map(angular.copy);

However you should be warned that a deep copy could be very expensive, and therefore only be used when truly necessary.

FYI: if you encounter a similar issue but not using Angular, you could use Lodash which also has a deep clone method.

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

4 Comments

had some problems with $watch(), and changed angular.copy($scope.data) > $.extend(true, {}, $scope.data); now is not showing RangeError: Maximum call stack size exceeded
What kind of problem did you have with $watch?
RangeError: Maximum call stack size exceeded
And you have the same problem using $.extend?

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.