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

1

3 Answers 3

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

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

1 Comment

Works perfect. Thank you.
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);

Comments

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);

Comments

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.