Dynamically change ng model source

I have delivery and billing fields. If the customer checks the "Use delivery for billing" field, I want the billing fields to match the delivery fields. I could copy the values, but I would prefer to bind the billing fields to the sending again, so if the checkbox is checked and the shipping changes are made, the billing will also be updated. So, how would I strip the source of the ng model, or what idiom could I use to bind the billing address fields to achieve this?

+4
source share
2 answers

Support two objects

$scope.shipping = { .... }; $scope.billing = { .... }; 

If someone chooses what they want to combine, just do

 $scope.billing = $scope.shipping. 

Since the objects are by reference, since they update one, the other will also be updated. You can remove the link by changing $ scope.billing back to what you initialized it:

 $scope.billing = { .... }; 

If you have a checkbox that you want to associate with this, connect data-ng-change to it

 <input type="checkbox" data-ng-model="MY_MODEL" data-ng-change="myFunction() "/> 

Then your controller has

 $scope.MY_MODEL = false; $scope.myFunction(){ console.log($scope.MY_MODEL); } 

Or don't bind data-ng-change and just $ watch MY_MODEL:

 $scope.MY_MODEL = false; $scope.$watch("MY_MODEL", function(){ console.log($scope.MY_MODEL); }, true); 
+4
source

You can use ng-checked instead of using the clockwork to make it easy. Do not reinvent the wheel.

 <input type="checkbox" ng-model="flip" ng-checked="checked();"> $scope.checked = function(){ if($scope.flip){ $scope.data = ... //update the data source }else{ $scope.data = ... //update the data source } } 
+3
source

Source: https://habr.com/ru/post/1500774/


All Articles