Angular Data Binding - Input type=“number”

前端 未结 5 1960
眼角桃花
眼角桃花 2021-01-05 05:36

I\'m having problems binding a number value using AngularJS.

I\'ve put a simplified example on JSFiddle: http://jsfiddle.net/treerock/ZvdXp/

5条回答
  •  走了就别回头了
    2021-01-05 05:58

    If you prefer to save a numeric value in the model, you can use a directive that convert the string generated by the text input and by the range input in a numeric value through the angular parser, like so:

    myApp.directive('numericsaving', function () {
        return {
            restrict: 'A',
            require: '?ngModel',
            scope: {
                model: '=ngModel'
            },
            link: function (scope, element, attrs, ngModelCtrl) {
                if (!ngModelCtrl) {
                    return;
                }
                ngModelCtrl.$parsers.push(function (value) {
                    if (!value || value==='' || isNaN(parseInt(value)) || parseInt(value)!==value) {
                        value=0;
                    }
                    return parseInt(value);
                });
            }
        };
    });
    

    In the HTML, leave the number input as is and add the directive in the others inputs this way:

    
    
    
    

    The angular parser will translate the string input in a numeric value before saving it in model, so the numeric input will automatically work. Here the complete fiddle.

    Moreover, if the user inserts letters or any strange character in the text input, they will not be saved in the model, preventing invalid value in the single source of truth of your application. Only '+' and '-' character at the begin of the text will be correctly parsed, so even negative value are allowed. I hope this helps! :)

提交回复
热议问题