8 javascript data-binding angularjs
我在使用AngularJS绑定数值时遇到问题.
我在JSFiddle上放了一个简单的例子:http://jsfiddle.net/treerock/ZvdXp/
<div ng-controller="MyCont" ng-app>
<input type="number" min="0" max="50" value="{{value}}" ng-model="value" />
<input type="text" value="{{value}}" ng-model="value" />
<input type="range" min="0" max="50" value="{{value}}" ng-model="value" />
{{value}}
</div>
Run Code Online (Sandbox Code Playgroud)
这应该是三种不同类型的输入字段,如果更新一个,则应更新所有值.除了数字输入之外,这是有效的.例如,如果我在第一个数字框中输入20,它会更新所有其他值的实例.但是,如果我更新文本或范围输入,则数字输入变为空白.
我想知道问题是如何在字段之间表示/转换数字.例如,数字输入是一个浮点数,文本输入是一个字符串?
您也可以使用指令修复此问题.我创建了一个指令来强制绑定到数字字段的输入为数字.
HTML:
myApp.directive('numericbinding', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
model: '=ngModel',
},
link: function (scope, element, attrs, ngModelCtrl) {
if (scope.model && typeof scope.model == 'string') {
scope.model = parseInt(scope.model);
}
}
};
});
Run Code Online (Sandbox Code Playgroud)
您可以将它添加到您的数字字段,如下所示:
<input data-ng-model="stringnumber" numericbinding type="number"/>
Run Code Online (Sandbox Code Playgroud)
完整示例:http://jsfiddle.net/tdjager/cMYQ3/1/
我已经扩展了Tim的答案,以便在用户更新控件值后使其更正数据类型.
myApp.directive('numericbinding', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
model: '=ngModel',
},
link: function (scope, element, attrs, ngModelCtrl) {
if (scope.model && typeof scope.model == 'string') {
scope.model = parseInt(scope.model);
}
scope.$watch('model', function(val, old) {
if (typeof val == 'string') {
scope.model = parseInt(val);
}
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34121 次 |
| 最近记录: |