Binding two inputs to the same model

Justin Dearing picture Justin Dearing · Jul 17, 2014 · Viewed 14.2k times · Source

As demonstrated in this plunker, I'd like to have an <input type="number"/> <input type="range"/> which both update the same $scope variable, as well as each other.

Right now, when I update one input the $scope variable is changed, but the value of the other scope is blanked. Do I just need to bind one with data-ng-model and use data-ng-change on the other? Is there a cleaner solution?

Answer

user2882597 picture user2882597 · Jul 17, 2014

Here's the example that I will be referencing. The problem is that range is a string value while number is an number value.

Instantiate a variable within your controller and write the function to handle conversion

$scope.data = 10;

$scope.setDataAsNumber = function() {
  $scope.data = parseInt($scope.data, 10);
}

Create all your elements bound to $scope.data

<input type="text" ng-model="data" ng-change="setDataAsNumber()">
<br>
<input type="number" ng-model="data">
<br>
<input type="range" ng-model="data" ng-change="setDataAsNumber()">
<br>
{{ data }}

I have solved this using ng-change directive.