Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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
share|improve this question
add comment

1 Answer

up vote 4 down vote accepted

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.

share|improve this answer
    
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. –  Hawk Sep 4 '13 at 10:56
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.