2

So I am working on a project using AngularJS where I need to be able to compare the values of an object in the scope with it's previously recorded values. I'm doing this through an algorithm such as the one below:

function() {
    var data = [
        { id: 1, key: 'value', foo: 'bar'},
        { id: 2, key: 'value', foo: 'bar'}
    ]
    $scope.oldTarget = data[0];
    $scope.target = data[0];
}

Now if I were to do:

function() {
    $scope.target.foo = 'fighters';

    if ($scope.target != $scope.oldTarget) console.log('Target was modified');
    console.log($scope.target);
    console.log($scope.oldTarget);
}

It will output:

{ id: 1, key: 'value', foo: 'fighters'}
{ id: 1, key: 'value', foo: 'fighters'}

My assumption is that AngularJS is automatically binding the two variables target and oldTarget and mirroring any changes done to target to oldTarget. Is this the case, and if so, is there anyway for me to prevent this? If not, what am I doing that's causing it to do this?

stanier
  • 45
  • 3

3 Answers3

1

I assume that this is not angular, this is just how it works, because $scope.oldTarget and $scope.target both is links to the same object.

var test = {foo : 'bar'};
var newTest = test;
newTest.foo = 'changed';
console.log(test);

Th output is: "Object {foo: "changed"}"

http://jsfiddle.net/rf0ac6zf/

Rasalom
  • 3,101
  • 3
  • 21
  • 29
1

This is not related to Angular, it's default JavaScript behavior. You are referencing the same object. If you intend to modify it without changing the source, you need to clone the object.

Take a look:

Community
  • 1
  • 1
Thiago Negri
  • 5,221
  • 2
  • 28
  • 39
0

Looks like your array element is being referenced "by reference". So create new instances of the element like this:

$scope.oldTarget = $.extend(null,data[0]);
$scope.target = $.extend(null,data[0]);
MarzSocks
  • 4,229
  • 3
  • 22
  • 35