I have shipping and billing fields. If a customer checks a box for "use shipping for billing", I want the billing fields to match the shipping fields. I could copy over the values, but I would rather re-bind the billing fields to match the shipping ones so if the box is checked and a change is made to shipping, the billing will also update. So how would I re-bind the source of ng-model or what idiom could I use to bind the billing address fields to achieve this?
Asked
Active
Viewed 1,999 times
2 Answers
4
Maintain two objects
$scope.shipping = { .... };
$scope.billing = { .... };
If someone selects that they want to match, just do
$scope.billing = $scope.shipping.
Since objects are by reference, as they update one the other will also update. You can remove the reference by changing $scope.billing back to whatever you initialized it with:
$scope.billing = { .... };
If you have a checkbox that you want to bind this too, wire up a data-ng-change on it
<input type="checkbox" data-ng-model="MY_MODEL" data-ng-change="myFunction() "/>
Then in your controller have
$scope.MY_MODEL = false;
$scope.myFunction(){
console.log($scope.MY_MODEL);
}
Or don't bind data-ng-change and just $watch the MY_MODEL:
$scope.MY_MODEL = false;
$scope.$watch("MY_MODEL", function(){
console.log($scope.MY_MODEL);
}, true);

Mathew Berg
- 28,625
- 11
- 69
- 90
-
Ok nice, that works! What would be the best way to bind/reset based on if the checkbox is checked or not? – chris Sep 05 '13 at 16:26
-
Ok that is almost working but for some reason the data binding on the checkbox isn't updating. If i set MY_MODEL to true, it is initially checked but when I uncheck it, myFunction() logs it as true still. Vice versa if it is initially false. Does the change event intercept data binding? – chris Sep 05 '13 at 16:42
-
Using $scope.$watch on MY_MODEL doesn't fire the callback when the checkbox is clicked – chris Sep 05 '13 at 16:52
-
http://stackoverflow.com/questions/18642371/checkbox-not-binding-to-scope-in-angularjs – chris Sep 05 '13 at 17:27
3
You can use ng-checked
instead of using scope watch to make it light weighted. Don't 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
}
}

zs2020
- 53,766
- 29
- 154
- 219
-
This would probably also work except that for some reason my checkbox isn't binding to the model properly http://stackoverflow.com/questions/18642371/checkbox-not-binding-to-scope-in-angularjs – chris Sep 05 '13 at 17:27