角度数据绑定 - 输入类型="数字"

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,它会更新所有其他值的实例.但是,如果我更新文本或范围输入,则数字输入变为空白.

我想知道问题是如何在字段之间表示/转换数字.例如,数字输入是一个浮点数,文本输入是一个字符串?

m.e*_*roy 11

你是对的,它与字符串与数字类型有关.我用一个$scope.watch声明来解决它:http: //jsfiddle.net/ZvdXp/6/


Tim*_*Tim 5

您也可以使用指令修复此问题.我创建了一个指令来强制绑定到数字字段的输入为数字.

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/


AJ *_*son 5

我已经扩展了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)