Wasimakram Mulla
Wasimakram Mulla

Reputation: 511

Variables changing value automatically without any link in AngularJS

I have two variables in my controllers in AngularJS i.e

_this.currentData=new Array();
_this.masterCurrentData=new Array();

Later I created another temporary Array of Objects and filled separately using loops etc.

var tmpDataSort=[{
    "values":new Array(),
             disabled: false,
            "key":"Retail"
        },{
            "values":new Array(),
             disabled: true,
            "key":"Commercial"
        },{
            "values":new Array(),
             disabled: true,
            "key":"Industrial"
        },{
            "values":new Array(),
             disabled: true,
            "key":"Residential"
        }]
_this.masterCurrentData=tmpDataSort;
_this.currentData=tmpDataSort;
tmpDataSort=null;

Later whenever I am performing an operation on Current Data automatically the value of MasterCurrentData is changing and I have never used masterCurrent Data

_this.modifyCurrentBean = function(locName, selectFlag){
    console.log(_this.masterCurrentData[0].values)
        for(var i=0;i<_this.currentData.length;i++){
            for(var j=0;j<_this.currentData[i].values.length;j++){
                if(_this.currentData[i].values[j].x==locName){                      
                    _this.currentData[i].values.splice(j,1);
                    break;
                }
            }
        }
        console.log(_this.masterCurrentData[0].values)
    }

The first console shows [object object] and the second console show only an single [object]

Upvotes: 0

Views: 54

Answers (1)

Egan Wolf
Egan Wolf

Reputation: 3573

You assign tmpDataSort to _this.currentData and _this.masterCurrentData, so by changing _this.currentData you change tmpDataSort and _this.masterCurrentData as well. You can make a copy of tmpDataSort using _this.currentData=angular.copy(tmpDataSort);

Upvotes: 2

Related Questions