HTML:
<input production-qty type="text" maxlength="3" ng-model="qty1">
Directive:
app.directive('productionQty', function() {
return {
require: 'ngModel',
link: function (scope, element, attr, ngModelCtrl) {
function fromUser(text) {
var transformedInput = text.replace(/[^0-9]/g, '');
console.log(transformedInput);
if(transformedInput !== text) {
ngModelCtrl.$setViewValue(transformedInput);
ngModelCtrl.$render();
}
return transformedInput; // or return Number(transformedInput)
}
ngModelCtrl.$parsers.push(fromUser);
}
};
});
Plunker
See also filters on ng-model in an input. My answer above is modeled off pkozlowski.opensource's answer.
I looked at ng-pattern, but it does not filter what is shown in the textbox. It sets $scope.qty1
to undefined
, but the undesired characters are visible in the textbox.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…