khet
khet

Reputation: 95

How can I prevent scope variable from changing whenever the model value changes in Angular JS

Here is my controller function in typescript:

let temp = null;

temp = _.find(this.scope.model.maintenanceArray, 
         function(_data,_key) {
           return _data.iD === currentId;
}
this.scope.originalData = temp;
this.scope.maintenanceData = temp;

And in the view,

<input type="text" class="form-control" name="dateFrom"         
placeholder="{{dateDefault}}"
ng-model="maintenanceData.from" required />

Basically I used maintenanceData for ngModel and want to keep originalData as it is. But the problem is that originalData is changed every time the model changes. How can I prevent originalData from updating?

Upvotes: 2

Views: 1299

Answers (1)

Nikolaj Dam Larsen
Nikolaj Dam Larsen

Reputation: 5684

This happens because the variable temp is passed by reference to both originalData and maintenanceData, so both of those variables reference the same object. To avoid this you can create a copy of the temp object for one of the two variables. Like this:

this.scope.originalData = angular.copy(temp);
this.scope.maintenanceData = temp;

There are several other ways to copy objects out there, so this is just one example.

Upvotes: 4

Related Questions