0
votes

I am really new to AngularJS so my question might be a bit silly. I am trying to solve a problem where I have two input fields which uses the same ng-model and I'd like the put value in one field not have the other input field displaying that value. I know it is desired that when I type in some value in one of the input fields it automatically reflects in the other. I wonder if there's any work around so that when I put value in one input, it does not show up in the other input field.

1
Minimal, Complete, and Verifiable example Add your code , what have you tried.Morse
By definition, ng-model is bound to a controller (or scope) property. If you don't want it dynamic, just don't use ng-model on the one you don't want changed. If you want them to change independently, use two separate controller properties. And perhaps instantiate them from same source. Why are you using the same ng-model in the first place? You're asking us: "Can I pour water on something and keep it dry at the same time?" Technically it might be possible, but why would you pour water in the first place if the goal is to keep the thing dry?tao
I have a radio button associated with each input field so user gets to choose an option and then type in the value. I use ng-model because essentially those two input fields correspond to one variable but my problem now turns into the value I entered in one input field gets displayed in the other.Sydney Chang
Use different ng-model properties and handle the logic inside controller.tao
This might sound really weird, but do I know you from middle school? I know this is off-topic but I'm just really surprised!Rebecca Bibye

1 Answers

0
votes

Here's how you can achieve this:

<input ng-model="foo">
<input value="{{::foo}}">

The second inputs' value will be set to the initial value of foo but it's one time bound. Changing foo after this will no longer affect it.

Furthermore, if you want the second input to update the first but the first not to update the second, you could go:

<input ng-model="foo">
<input ng-init="bar=foo" 
       ng-model="bar" 
       on-change="updateFoo()">

// And, inside controller:

$scope.updateFoo = function() {
  $scope.foo = $scope.bar;
};