提案された解決策はどれもうまくいきませんでした。数時間後、ついに道を見つけました。
これは角度ディレクティブです:
angular.module('app').directive('restrictTo', function() {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var re = RegExp(attrs.restrictTo);
var exclude = /Backspace|Enter|Tab|Delete|Del|ArrowUp|Up|ArrowDown|Down|ArrowLeft|Left|ArrowRight|Right/;
element[0].addEventListener('keydown', function(event) {
if (!exclude.test(event.key) && !re.test(event.key)) {
event.preventDefault();
}
});
}
}
});
入力は次のようになります。
<input type="number" min="0" name="inputName" ng-model="myModel" restrict-to="[0-9]">
正規表現は、値ではなく、押されたキーを評価します。
type="number"
また、値を変更できないため、入力でも完全に機能するため、キーは表示されず、モデルを台無しにしません。