简体   繁体   中英

Angular js- When I Make a change in one scope variable it also changes other scope variable

As per title I have uploaded my code on fiddle here is the link visit
https://jsfiddle.net/owze1rcj/ when I make changes myAppObjects variable. changes also reflect in other variable. here is my code
(HTML part)

<div ng-controller="MyCtrl">
    <table>
    <tr ng-repeat="appObj in myAppObjects">
        <td>{{appObj.id}}
            <input type="checkbox" ng-model="appObj.cb1"></td>
        <td><input type="checkbox" ng-model="appObj.cb2"></td>
        <td><input type="checkbox" ng-model="appObj.cb3"></td>
        <td><input type="checkbox" ng-model="appObj.cb4"></td>
        <td><input type="checkbox" ng-model="appObj.cb5"></td>
    </tr>
    </table>
    <pre>
   first {{myAppObjects | json}}
    second {{AppObjects | json}}
    </pre>

</div>

(Controller part)

function MyCtrl($scope) {
    var a =[
        {
        id: 1,
        cb1: true,
        cb2: false,
        cb3: true,
        cb4: true,
        cb5: false
        }];

    $scope.myAppObjects = a;
    $scope.AppObjects = a;


}

First Understand the concept of Deep copy and Shallow Copy

Shallow copy

Shallow copy has the top level object and points to the same object.

Hence, When you directly copy the one scope variable to other it creates a shallow copy .

  $scope.firstVar = $scope.secondVar;

Here, both firstVar and secondVar are connected to each other in above example.

Deep copy

Deep copy has all of the objects of the copied object at all levels and points to the different object.

angular.copy Creates a deep copy of source, which should be an object or an array.

$scope.firstVar = angular.copy($scope.secondVar);

Here, both firstVar and secondVar are two different variable.

function MyCtrl($scope) {
var a =[
    {
    id: 1,
    cb1: true,
    cb2: false,
    cb3: true,
    cb4: true,
    cb5: false
    }];

$scope.myAppObjects = angular.copy(a);
$scope.AppObjects = angular.copy(a);
}

Use angular.copy() method for assigning values, it won't copy variable references

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM