Angular - how to one-way link two input values?

3.2k views Asked by At

I have a large HTML form with lots of text. There are some duplicated input fields and customer wants to prefill bottom fields with values filled earlier, but without affecting already filled inputs.

Think about it as in the following scenario: you are filling a licence agreement and enter your name in a textbox. Then at the end of the document there again is an input box for your name next to signature field. This name field should be filled with the value you entered before. But there might be situations when another person will sign the document on your behalf, and then both fields will differ.

Obviously, I cannot just link both fields to single model because the bottom field must be independent. It should be changed only if the top field changes, but not vice versa.

Is there any way I can achieve such one way binding for both fields, but keeping them linked to separate models?

I'd prefer some trick that can be used inside HTML to avoid coding Javascript logic, if possible, because this HTML form is stored in database as a document template and I'd like to avoid adding lots of Javascript to it.

2

There are 2 answers

3
Riad Baghbanli On BEST ANSWER
<input ng-change="secondVal = firstVal" ng-model="firstVal">
...
<input ng-model="secondVal">
0
Okazari On

Consider using ng-change to update the other value :

HTML

<input ng-change="updateNameBot()" ng-model="nameTop">
<input ng-model="nameBot">

Controller

$scope.updateNameBot = function(){
      $scope.nameBot = $scope.nameTop;
}