问题
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