将两个输入绑定到同一个模型 [英] Binding two inputs to the same model

查看:35
本文介绍了将两个输入绑定到同一个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如这个 plunker 中所示,我想要一个 <input类型=数字"/><输入类型=范围"/>它们都更新相同的 $scope 变量,以及彼此.

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.

现在,当我更新一个输入时,$scope 变量发生了变化,但另一个作用域的值是空白的.我是否只需要将一个与 data-ng-model 绑定并在另一个上使用 data-ng-change?有没有更干净的解决方案?

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?

推荐答案

这是我将引用的示例.问题是 range 是一个字符串值,而 number 是一个数字值.

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);
}

创建绑定到 $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 }}

我已经使用 ng-change 指令解决了这个问题.

I have solved this using ng-change directive.

这篇关于将两个输入绑定到同一个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆