Search code examples
javascriptangularjsangularjs-scope

AngularJS $scope variable changing value for no reason?


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


Solution

  • $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