T
T
timofy2018-03-09 18:56:25
Angular
timofy, 2018-03-09 18:56:25

How to avoid "over-binding" in AngularJs?

The point is this: in the user's personal account, I am creating functionality with which the user could change his personal data. It looks like this: already existing user data is loaded from the server. The page has a form with fields that display existing user data. These fields look something like this:
<input ng-model="myData.name">(using the ng-model angular binding)
The user will be able to change their data by adjusting them in these fields. There are two buttons at the end of the form: "Save changes" and "Cancel changes". In order for the "Cancel changes" button to work, I wrote this:
$scope.user = $rootScope.myData
that is, in order to save the already existing user data in the $scope.user object, and then if the user clicks "Cancel changes" - in this case, the function that "restores" the data will work.
This is how I made this function:

$scope.cancel = function () {
      $rootScope.myData  =  $scope.user;
}

But as it turned out: if you change the data in the field (which is attached
to the object $rootScope.myData), then they change not only in the $rootScope.myData object, but also in the $scope.user object. Some kind of "too wise" binding in AngularJs: it changes the data not only in the object to which it is attached, but also in the one from which the data is copied to the attached object.
Is it possible to somehow prevent this or write this functionality without the Angular binding?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-03-09
@timofy

$scope.user = $rootScope.myData

copied data

Not copied. When assigning objects, not values ​​are copied, but references. Copying, it's a little more complicated: Or
$scope.user = Object.assign({}, $rootScope.myData)
$scope.user = { ...$rootScope.myData }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question