How to synchronize 2 objects based on a checkbox change?

I'm in the early stages of Angularjs training, so please carry me around to ask this stupid question. I basically want to do this from the start, and not just make it work.

In any case, I have 1 order form, which contains 2 sets of addresses: sending and billing. I have a flag that says: "The delivery address is the same as the billing address", which, if the flag is to synchronize 2 addresses.

My approach is that 2 addresses will be treated as 2 objects, and if the box is checked, then I will have something like scope.shippingAddress = scope.billingAddress.

I wonder if this is good to do?

Also, what is a good way to trigger the above sync when changing a checkbox? Should I use ng-checked or should $ watch be used perhaps?

+4
source share
1 answer

I would use a watch:

$scope.$watch('shippingIsSameAsBilling', function(value) {
  if(value) {
    $scope.shippingAddress = $scope.billingAddress;
  } else {
    $scope.shippingAddress = angular.copy($scope.shippingAddress);
  }
});

You need to โ€œunsynchronizeโ€ the two addresses if the user again disables this flag, assigning each his own object (using angular.copy).

See this Plunker for a working example.

Please note that you will send two identical addresses to your internal server. Are you sure you want to do it this way?

+4
source

All Articles