AngularJS:带数字输入的双向数据绑定
AngularJS: Two-Way Data Binding with Number Inputs
我试图使用角数据绑定input type="number"
元素,但我似乎无法弄清楚如何获得绑定工作。例如,当我更新任何值时,我希望绑定到它的值也更新。
JSBin: http://jsbin.com/kiqivule/3/edit
使用$watch
:
app.controller('MyCtrl', function($scope) {
$scope.tires = $scope.bikes * 2;
$scope.$watch('bikes', function(){
$scope.tires = $scope.bikes * 2;
});
});
你想要实现的不是双向绑定。
app.controller('MyCtrl', function($scope) {
$scope.tires = $scope.bikes * 2;
});
上面的代码只会在调用控制器时设置tires的值,而不会在bikes的值发生变化时设置。这可以通过在自行车上添加一个手表来实现,当自行车的值发生变化时,它会显示值
app.controller('MyCtrl', function($scope) {
$scope.$watch('bikes', function(){
` $scope.tires = $scope.bikes * 2;`
})
});
两种方式:
1 -"ng-change:
<input type="number"
ng-change="tires = bikes * 2"
min="0" ng-model="bikes" placeholder="Bikes" id = "bikes"/>
还是……
2- $watch
:
app.controller('MyCtrl', function($scope) {
$scope.$watch('bikes', function(newValue, oldValue) {
if(newValue === oldValue) {
return; // Angular calls watch at initialization with no change
}
$scope.tires = $scope.bikes * 2;
});
});
试试这个:
在html 使用ng-change:<input type="number" min="0" ng-model="bikes" placeholder="Bikes"
ng-change="Calc()" id = "bikes"/>
在JS $scope.Calc = function(){
$scope.tires = $scope.bikes * 2;
};
希望能有所帮助.........
以下几点:
-
你应该在一个"model"类型的属性中定义你的模型——详细信息见这里:http://zcourts.com/2013/05/31/angularjs-if-you-dont-have-a-dot-youre-doing-it-wrong/
-
为了更新"tires"属性,你需要"观察"bikes"属性的变化。
这是一个更新的JSBin,展示了如何做到这一点:http://jsbin.com/kiqivule/15/edit?html,js,output
更新首先,$watchGroup只在v1.3.0-beta版本出现。在你的脚本中,你使用的是v1.2.10.
其次,这里引用的所有jsbin都显示,当脚踏车属性更新时,tires属性也在更新。下面是另一个jsbin,它更清楚地显示了这一点。
所以我还是不知道你在追求什么?
- 在VanillaJS中模拟模型双向数据绑定
- Telerik rad组合框多列数据绑定
- 数据绑定:'系统Char'不包含名为'xxxxx'
- 绑定Range输入以修改样式
- OnsenUI AngularJS数据绑定无法正常工作
- 数据绑定在带有输入标签的 AngularJS 中不起作用
- Angular2:如何在输入元素上动态设置数据绑定变量
- AngularJs 双向数据绑定不适用于自定义指令输入元素
- 角度数据绑定 - 输入类型=“数字”
- 2 个输入字段上的单向数据绑定
- 我的数据绑定有效,但我的输入ng模型是't更新时更新
- 输入类型text和email在angular指令中的行为不同(双向数据绑定)
- 如何在React中进行两天的数据绑定,当输入值A更新时B更新,反之亦然,同时保留以前转换的历史记录
- 如何使用react进行双向数据绑定,使输入值A在B更新时更新,反之亦然
- js输入类型日期数据绑定在谷歌Chrome
- AngularJS:带数字输入的双向数据绑定
- Emberjs:数字输入之间的双向数据绑定
- 有没有可能在Vue.js中没有输入元素的双向数据绑定?
- 使用JQuery设置输入值后,数据绑定不会更新
- 如何使用AngularJS将html输入标记中的数据绑定到javascript对象