Binding two inputs to the same model

一个人想着一个人 提交于 2019-12-07 19:24:17

问题


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?


回答1:


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.




回答2:


Not sure why this is, but when you change the type="number" to type="text" it works.

I found this workaround for input type="number" but seems a bit hacky:

$scope.$watch('MyNumber',function(number) {
  $scope.MyNumber = Number(number);
});


来源:https://stackoverflow.com/questions/24808020/binding-two-inputs-to-the-same-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!