我正在尝试为货币值创建一个自定义输入指令,其侧面有两个按钮来增加和减少值。
现在它正在工作,但是当用户输入一些文本时,数字没有格式化。我做错了什么?
工作小提琴: https://jsfiddle.net/x8L74g75/3/
这是自定义指令:
app.directive('inputMoney', ['$locale', '$filter', function ($locale, $filter) {
var numberFilter = $filter('number');
return {
restrict: 'E',
scope: {
ngModel: '=',
ngDisabled: '=?',
min: '=?',
max: '=?'
},
require: 'ngModel',
template: '<button type="button" class="increment" ng-click="increment(-10)" ng-disabled="ngDisabled">–</button>' +
'<input type="tel" ng-model="ngModelCtrl.$viewValue" ng-disabled="ngDisabled" min="min" max="max" autofocus required autocomplete="off">' +
'<button type="button" class="increment" ng-click="increment(10)" ng-disabled="ngDisabled">+</button>',
link: function ($scope, $element, $attr, ngModel) {
var $input = $element.find('input');
$scope.ngModelCtrl = ngModel;
ngModel.$parsers.push(function inputMoneyParser(value) {
var rawNumber = value + '';
while (rawNumber.indexOf($locale.NUMBER_FORMATS.GROUP_SEP) >= 0) {
rawNumber = rawNumber.replace($locale.NUMBER_FORMATS.GROUP_SEP, '');
}
return parseInt(rawNumber);
});
$scope.$watch('ngModelCtrl.$viewValue', ngModel.$setViewValue);
//Group separator
ngModel.$formatters.push(function inputMoneyFormatter(value) {
return numberFilter(value);
});
//Validators
ngModel.$validators.value = function (modelValue, viewValue) {
return !isNaN(modelValue) && isFinite(modelValue);
};
ngModel.$validators.min = function (modelValue, viewValue) {
return angular.isUndefined($scope.min) ? true : modelValue >= $scope.min;
};
ngModel.$validators.max = function (modelValue, viewValue) {
return angular.isUndefined($scope.max) ? true : modelValue <= $scope.max;
};
$scope.$watch('ngModelCtrl.$valid', function (isValid) {
$input.toggleClass('ng-invalid ng-dirty', !isValid);
});
//Only allow numbers and group separator input
$input.on('keypress', function inputMoneyKeyPress(e) {
var charCode = angular.isUndefined(e.which) ? e.keyCode : e.which;
var charStr = String.fromCharCode(charCode);
if (charStr && charStr != $locale.NUMBER_FORMATS.GROUP_SEP && /[^\d]/gi.test(charStr)) { //Disable alpha input
e.preventDefault();
}
});
//Increment buttons
$scope.increment = function incrementMoney(increment) {
if (!$scope.ngDisabled) {
$scope.ngModel = ($scope.ngModel || 0) + increment;
}
};
}
};
}]);
答案 0 :(得分:0)
由于范围问题,在键入文本时不会调用格式化程序函数。因此,我更改了代码以调用模糊函数。
'<input type="tel" ng-model="ngModelCtrl.$viewValue" .. ng-blur="format()">'
$scope.format = function(){
ngModel.$viewValue = numberFilter(ngModel.$modelValue);
};
答案 1 :(得分:0)