更改时,输入模型从Integer更改为String

Chr*_*all 37 javascript integer angularjs

根据输入模型提供一种价格范围/评级功能.在加载时,当它从后端设置时,它以整数开始,但是当你输入它时,它会变成一个字符串.在Angular中有什么方法可以将输入的值声明为整数吗?

HTML:

<input type="text" name="sellPrice" id="sellPrice" class="sell-price" data-ng-model="menu.totalPrice" data-ng-change="updateMenuPriceRange()"required>
Run Code Online (Sandbox Code Playgroud)

JS:

$scope.updateAggregatePricing();

if ($scope.menu.totalPrice === 0) {
    $scope.menuPriceRange = "";
} else if ($scope.menu.totalPrice < 10) {
    $scope.menuPriceRange = "$";
} else if ($scope.menu.totalPrice >= 10 && $scope.menu.totalPrice <= 12.50) {
    $scope.menuPriceRange = "$$";
} else if ($scope.menu.totalPrice >= 12.51 && $scope.menu.totalPrice < 15) {
    $scope.menuPriceRange = "$$$";
} if ($scope.menu.totalPrice >= 15) {
    $scope.menuPriceRange = "$$$$";
} else {
    $scope.menuPriceRange = "";
}
Run Code Online (Sandbox Code Playgroud)

Yan*_*ans 85

我知道我迟到但我想我会发布这个答案,因为其他人可能仍在寻找其他选择.

您可以使用AngularJS指令链接函数来解决此问题.代码:

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);
            });
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

然后,您将在输入元素上使用此指令,以确保输入的任何值都被解析为整数.(显然这个例子没有验证输入,以确保输入的内容实际上是一个整数,但你可以通过使用正则表达式轻松实现这一点)

<input type="text" ng-model="model.value" integer />
Run Code Online (Sandbox Code Playgroud)

有关此主题的更多信息可以在表单上的AngularJS文档中找到,就在"自定义验证"部分:http://docs.angularjs.org/guide/forms.

编辑:更新了parseInt()调用以包含基数10,如adam0101所示

  • 您应该在parseInt(viewValue,10)中包含10的基数,否则在某些浏览器实现中,前导零可能会给出意外值. (4认同)

pko*_*rce 23

是的,使用类型的输入number:

<input type="number" name="sellPrice" ...>
Run Code Online (Sandbox Code Playgroud)


Chr*_*all 8

在我的条件之前,将模型解析为整数.

$scope.menu.totalPrice = parseInt($scope.menu.totalPrice, 10);
Run Code Online (Sandbox Code Playgroud)