javascript - 형변환 - 파이썬 숫자를 문자로
변경시 입력 모델이 정수에서 문자열로 변경됨 (3)
Yanik의 대답과 매우 흡사합니다. 시도해 보니 작동하지 않았습니다. AngularJS 설명서의이 버전은 완벽하게 작동합니다.
.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);
});
}
};
});
입력 모델을 기반으로 한 가격 범위 / 등급 기능을 보유하십시오. 로드시 백엔드에서 설정되면 정수로 시작하지만 입력하면 문자열로 변경됩니다. 입력 값을 정수로 선언하기 위해 Angular에 어떤 방법이 있습니까?
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 = "";
}
나는 늦었지만 다른 사람들이 여전히 대안을 찾고 있을지도 모르겠다 고 대답했다.
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);
});
}
};
});
그런 다음 입력 요소에이 지시문을 사용하여 입력 한 값이 정수로 파싱되는지 확인합니다. (분명히이 예제는 실제로 입력 된 내용이 정수인지 확인하기 위해 입력을 검증하지 않지만, 예를 들어 정규 표현식을 사용하여 쉽게 구현할 수 있습니다)
<input type="text" ng-model="model.value" integer />
이 주제에 대한 자세한 내용은 양식의 AngularJS 문서에서 "Custom validation"섹션 ( http://docs.angularjs.org/guide/forms .
편집 : adam0101에서 제안한 것처럼 radix 10을 포함하도록 parseInt()
호출을 업데이트했습니다.
조건부로 모델을 정수로 파싱하는 작업을 마쳤습니다.
$scope.menu.totalPrice = parseInt($scope.menu.totalPrice, 10);