3

I've set up a small fiddle here http://jsfiddle.net/SPMfT/137/ and I was wondering if someone could explain me why changing an object doesn't work, while changing properties of the object, or changing the object with "$scope" in front works.

The reason is that I try to avoid using scope in controller functions so they will be easier to test.

My real task is an ng-click="reset(current, master)" with

$scope.reset = function (current, master) { angular.copy(current, master); }

This doesn't work, whereas this works:

$scope.reset = function (current, master) { angular.copy($scope.current, master); }

Both $scope.current and $scope.master exist

Cheers

Update:

My problem was I wasn't updating the object itself. To solve the problem use e.g.

angular.extend(data, { name: 'change', game:'change' });

or

angular.copy({ name: 'change', game:'change' }, data);//Pay attention to order
1
  • using angular.extend() was the ticket for me. thanks Commented Apr 7, 2016 at 4:28

1 Answer 1

7

The reason is you are creating a new object (and therefore a different reference) and assigning it to a local variable that was previously pointing to the same object.

$scope.change = function (data) {
    data = { name: 'change', game:'change' };
}

The data variable passed holds a reference to the same object of your $scope.data but you are assigning a local variable pointing to a reference of an object A to a new object B, locally. At that point, $scope.data still holds a reference to the same object it has before. All you are doing is changing the reference to the local variable and discarding it at the end of the function.

In your specific case, it should work (using current or $scope.current). I believe you are inverting the parameter in angular.copy as it should be (source, destination). See this updated fiddle for a simple demo.

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

1 Comment

Good explanation. You were of course right and I had the angular.copy mixed up. I realize now that I can use angular.extend(data, { name: 'change', game:'change' }); on the fiddle example.

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.