bigcat bigcat - 1 month ago 5
AngularJS Question

angular ng-model updates parent object after submission and stay bounded

I have a form and a display fields above it. I want to update display values only after submission. This works fine for the first submit. Until I submit it, values don't change, and once I click collect it updates values, and then, it seems that ng-model somehow binds and stay bounded to upper object, since when I continue to type on input fields values above update automatically. For me this is a strange behaviour, I want them to update only after I submit them. Any ideas?

and here is the code:



function Ctrl($scope) {
$scope.customFields = ["Age", "Weight", "Ethnicity"];
$scope.person = {
customfields: {
"Age": 0,
"Weight": 0,
"Ethnicity": 0
}
};
$scope.submited = {
"person" : {
"customfields" : {
"Age" : 0,
"Weight" : 0,
"Ethnicity" : 0
}
}
};

$scope.collectData = function () {
$scope.submited.person.customfields = $scope.person.customfields;
console.log($scope.person.customfields);
}
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="Ctrl">
<div ng-repeat="fields in submited.person.customfields">
{{fields}}
</div>
<div class="control-group" ng-repeat="field in customFields">
<label class="control-label">{{field}}</label>
<div class="controls">
<input type="text" ng-model="person.customfields[field]" />
</div>
</div>
<button ng-click="collectData()">Collect</button>
</div>




Answer

When you use:

$scope.submited.person.customfields = $scope.person.customfields;

the variables become clones of each other - it's a property in JS. Hence, when you bind using that object, the values stay bound. You're basically just creating another reference for an already existing object.

angular.copy copies only the structure and data of the object onto another. Hence, cloning takes place rather than creating a reference of the object.

Hence, change it to:

$scope.submited.person.customfields = angular.copy($scope.person.customfields);