Input model changes from Integer to String when changed

后端 未结 4 681
情深已故
情深已故 2020-12-05 06:57

Have a kind of price range/rating functionality based on an inputs model. On load, when it\'s set from the backend, it starts off as an integer, but when you type in it, it

相关标签:
4条回答
  • 2020-12-05 07:16

    Yes, use input of type number:

    <input type="number" name="sellPrice" ...>
    
    0 讨论(0)
  • 2020-12-05 07:23

    Very similar to the accepted answer from Yanik, except I tried that and it didn't work. This version from the AngularJS documentation is working perfectly for me, though.

    .directive('stringToNumber', function() {
        return {
            require: 'ngModel',
            link: function(scope, element, attrs, ngModel) {
              ngModel.$parsers.push(function(value) {
                return '' + value;
              });
              ngModel.$formatters.push(function(value) {
                return parseFloat(value);
              });
            }
          };
        });
    
    0 讨论(0)
  • 2020-12-05 07:34

    I know I'm late but I figured I'd post this answer as other people might still be searching for alternatives.

    You could solve this by using the AngularJS directive linking function. The code:

    var myMod = angular.module('myModule', []);
    
    myMod.directive('integer', function(){
        return {
            require: 'ngModel',
            link: function(scope, ele, attr, ctrl){
                ctrl.$parsers.unshift(function(viewValue){
                    return parseInt(viewValue, 10);
                });
            }
        };
    });
    

    You would then use this directive on an input element to make sure that any value you enter, gets parsed to an integer. (obviously this example doesn't validate the input to make sure that what was entered is in fact an integer, but you could easily implement this with the use of regular expressions for example)

    <input type="text" ng-model="model.value" integer />
    

    More information about this topic can be found on the AngularJS docs on forms, right around the section of "Custom validation": http://docs.angularjs.org/guide/forms .

    Edit: Updated parseInt() call to include the radix 10, as suggested by adam0101

    0 讨论(0)
  • 2020-12-05 07:35

    Ended up parsing the model as an integer before my conditional.

    $scope.menu.totalPrice = parseInt($scope.menu.totalPrice, 10);
    
    0 讨论(0)
提交回复
热议问题