我有一个指令,通过在用户输入时添加小数点来过滤货币。
我的问题是它不会允许否定。允许用户输入“ - ”符号并将其始终显示在数字的开头,或输入“+”并让它消失,这将是一件好事。
需要:
-
Check out my Plunker here。它有input = number
但不允许负数:
app.directive('format', ['$filter', function ($filter) {
return {
require: 'ngModel', //there must be ng-model in the html
link: function (scope, elem, attr, ctrl) {
if (!ctrl) return;
ctrl.$parsers.unshift(function (viewValue, modelValue) {
var plainNumber = viewValue.replace(/[^-+0-9]/g,'');
// use angular internal 'number' filter
plainNumber = $filter('number')(plainNumber / 100, 2).replace(/,/g, '');
// update the $viewValue
ctrl.$setViewValue(plainNumber);
// reflect on the DOM element
ctrl.$render();
// return the modified value to next parser
return plainNumber;
});
}
};
}]);
答案 0 :(得分:1)
这将完全按照您的意愿行事:
var app = angular.module('App',[]);
app.controller('MainCtrl', function ($scope) {
});
app.directive('format', ['$filter', function ($filter) {
return {
require: 'ngModel', //there must be ng-model in the html
link: function (scope, elem, attr, ctrl) {
if (!ctrl) return;
ctrl.$parsers.unshift(function (viewValue, modelValue) {
var plainNumber = viewValue.replace(/[^-+0-9]/g,'');
var newVal = plainNumber.charAt(plainNumber.length-1);
var positive = plainNumber.charAt(0) != '-';
if(isNaN(plainNumber.charAt(plainNumber.length-1))){
plainNumber = plainNumber.substr(0,plainNumber.length-1)
}
//use angular internal 'number' filter
plainNumber = $filter('number')(plainNumber / 100, 2).replace(/,/g, '');
if(positive && newVal == '-'){
plainNumber = '-' + plainNumber;
}
else if(!positive && newVal == '+'){
plainNumber = plainNumber.substr(1);
}
plainNumber.replace('.', ',');
//update the $viewValue
ctrl.$setViewValue(plainNumber);
//reflect on the DOM element
ctrl.$render();
//return the modified value to next parser
return plainNumber;
});
}
};
}]);
只需删除type ="数字"从:
<input ng-model="amount" format="number" />