Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change source of ng-model

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?

like image 947
chris Avatar asked Mar 22 '23 12:03

chris


1 Answers

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);
like image 192
Mathew Berg Avatar answered Apr 25 '23 04:04

Mathew Berg