Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

javascript - Input model changes from Integer to String when changed

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 changes to a string. Is there any way in Angular to declare the value of an input as integer?

HTML:

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

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 = "";
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...