75

Is there anyway that I can bind two model values to one input field?

Suppose I have input field which I want to be the value of two variables in the scope something like:

<input type="text" model="sn_number; id" > 
1
  • 1
    The answer is no. But more info would be useful so we could help with suggestions.
    – Greg
    Dec 15, 2012 at 8:28

4 Answers 4

140

You cannot, but there are some workarounds.

1. Use ngChange to update the other model

<input type="text" 
       ng-model="sn_number" 
       ng-change="id=sn_number"/> 

2. You could watch a model, and when in changes, update another

$scope.$watch('sn_number', function(v){
  $scope.id = v;
});

You would need to watch also for changes in id if you want to keep them in sync.

Example here

1
  • 3
    FYI: the reason this works is because ng-model has prio 1 while ng-change has prio 0 (as of Angular 1.5) and therefore is called first Mar 7, 2016 at 12:57
11

You can bind fields immediately, not only in ng-change, and actually it isn't data binding, its only angular expression

  <label>Name</label>
  <input type="text" ng-model="name" value="{{name}}"/>

  <label>Key</label>
  <input type="text" ng-model="key" value="{{key=name}}" />

2
  • It actually worked for me, but can you explain why is it working? why just using value ="{{name}}" won't work?
    – Gil404
    Feb 5, 2017 at 14:58
  • save my day from writing lots of $watch :)
    – maruf571
    Mar 9, 2017 at 17:33
7

It would make no sense to bind an input to two variables in the model. Binding works both ways, so if the model is updated, the field is updated and vice-versa. If you were to bind to two variables, what would be the single source of truth?

However you can use ng-change to call a method on the controller which can set two variables when the field changes.

0

with ng-init

<div ng-controller="ctrl" ng-init="model = { year: '2013', month:'09'}">

or

<div ng-repeat="c in contact" ng-init="likes = { food: 'steak', drink:'coke'}">
1

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.