【发布时间】:2016-05-18 05:09:15
【问题描述】:
我正在尝试编写一个限制用户输入的指令。在示例limit-directive="2" 中,用户只能在输入字段中键入两个字符。
我的问题是我的指令不起作用。它被调用,但不会通过返回 false 或 event.preventDefault(); 来停止按键。
关于我缺少什么的任何想法?
export class limitDirective implements angular.IDirective {
restrict = 'A';
constructor() {
if(console) console.log('limit directive invoked')
}
link = (scope: angular.IScope, element: angular.IAugmentedJQuery, attrs: angular.IAttributes) => {
var limit = parseInt(attrs.limitDirective);
angular.element(element).on("keypress", function(event) {
if (this.value.length >= limit){
var allowedKeys = [8, 9, 13, 35, 36, 37, 38, 39, 40, 46];
var key = event.which || event.keyCode;
if (allowedKeys.indexOf(key) < 0 ){
event.preventDefault();
}
}
});
}
static factory(): angular.IDirectiveFactory {
const directive = () => new limitDirective();
return directive;
}
}
【问题讨论】:
-
你能提供一个小提琴吗?我的猜测是你必须使用
keydown事件而不是keypress。此外,您可能希望明确指定parseInt的基数,例如parseInt(number, 10),因为旧版本的 EcmaScript 使用八进制作为默认基数。
标签: angularjs typescript angular-directive