Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind 2 models to one input field in Angular?

Tags:

angularjs

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" >  
like image 370
Adelin Avatar asked Dec 15 '12 07:12

Adelin


People also ask

How do I bind the data in an input field to another input field on angular?

[value]=“username” - Binds the expression username to the input element's value property. (input)=“expression” - Is a declarative way of binding an expression to the input element's input event (yes there's such event) username = $event. target.

Can ngModel have multiple values?

The solution is ng-bind-template, it can bind more than one {{}} expression, so it can show more than a single value that was declared in the Script function.

What is the difference between ngModel and [( ngModel )]?

The answer is: (ngModel) causes a 1-way data-binding, whereas [(ngModel)] ensures a two-way data binding.


1 Answers

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

like image 136
jaime Avatar answered Oct 12 '22 23:10

jaime