0

I have an angular controller that get's data using the $http.get() method. I assign the response data to $scope.foo and also $scope.bar.

I then bind $scope.foo to an input field using ng-model="foo", and then a $scope function $scope.buttonClick to a button using ng-click="buttonClick()".

When I change the value of the input field and select the button, $scope.buttonClick outputs both $scope.foo and $scope.bar and they appear to match the newly entered value. This is odd because I only binded $scope.foo. Why is this happening and how can I fix it?

controller:

angular.module('app')
.controller('controller', ($scope, $http) => {

    $document.ready(() => {

        $http.get('/data').then((res) => {
            $scope.foo = res.data;
            $scope.bar = res.data;
        });

        $scope.buttonClick = () => console.log($scope.foo, $scope.bar);
    });
});

(Uses ES6 Syntax) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Maximillion Bartango
  • 1,533
  • 1
  • 19
  • 34
  • Possible duplicate of [Why and when to use angular.copy? (Deep Copy)](http://stackoverflow.com/questions/33043850/why-and-when-to-use-angular-copy-deep-copy) – georgeawg Mar 17 '17 at 18:13

3 Answers3

5

$scope.foo and $scope.bar is pointing to the same property that is res.data. You must copy the objects:

$scope.foo = angular.copy(res.data);

You are assigning a reference to data property of res object instead of assigning the value of data property

Carlos Arauz
  • 805
  • 6
  • 8
1

This is a feature of angular JS two way data binding. If you assign same data into two different purpose, best way is get a copy

 $scope.foo = res.data;
 $scope.bar = angular.copy(res.data);
Dushyantha
  • 217
  • 2
  • 15
1

Use angular.copy when assigning the value of object or array to another variable and that object value should not be changed.

Without deep copy or using angular.copy, changing the value of object property will change the property value of all objects holding the same reference.

In your case $scope.foo and $scope.bar holding the same reference, so whenever you change the property of $scope.foo, $scope.bar is also getting updated. so you need to break the reference.

$scope.foo = angular.copy(res.data);
Pramod_Para
  • 671
  • 3
  • 10