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.
0
votes
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;
};
ng-model
is bound to a controller (or scope) property. If you don't want it dynamic, just don't useng-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 sameng-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? – taong-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 Changng-model
properties and handle the logic inside controller. – tao