변경 시 입력 모델이 Integer에서 String으로 변경됨
입력 모델에 근거한 일종의 가격대/등급 기능을 가지고 있다.로드 시 백엔드에서 설정하면 정수로 시작되지만 입력 시 문자열로 변경됩니다.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 = "";
}
늦은 건 알지만 다른 사람들이 아직 대안을 찾고 있을 수 있기 때문에 이 답을 올려야겠다고 생각했어요.
Angular를 사용하면 이 문제를 해결할 수 있습니다.JS 다이렉트링크 함수코드:
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 />
이 항목에 대한 자세한 내용은 Angular에서 확인할 수 있습니다.「커스텀 검증」섹션의 바로 근처에 있는 폼에 관한 JS 문서:http://docs.angularjs.org/guide/forms
편집: 갱신됨parseInt()adam0101에 의해 제안된 기수 10을 포함하기 위한 호출
예, 유형 입력 사용number:
<input type="number" name="sellPrice" ...>
결국 내 조건 앞에 모델을 정수로 해석하게 되었다.
$scope.menu.totalPrice = parseInt($scope.menu.totalPrice, 10);
Yanik이 받아들인 답변과 매우 유사하지만, 제가 시도했지만 효과가 없었습니다.Angular의 이 버전하지만 JS 문서는 완벽하게 작동하고 있습니다.
.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);
});
}
};
});
언급URL : https://stackoverflow.com/questions/15072152/input-model-changes-from-integer-to-string-when-changed
'source' 카테고리의 다른 글
| "현대" 브라우저는 한 번에 몇 개의 HTML 요소를 처리할 수 있습니까? (0) | 2023.02.14 |
|---|---|
| 프록시를 초기화할 수 없습니다. 세션 없음 (0) | 2023.02.14 |
| React + ES6 + 웹 팩을 사용하여 구성 요소를 가져오고 내보내는 방법은 무엇입니까? (0) | 2023.02.14 |
| MySQL 쿼리 런타임 감소 (0) | 2023.01.29 |
| MySql에서 기본값으로 함수를 사용할 수 있습니까? (0) | 2023.01.29 |