且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angular.js - 从输入中过滤无效字符的控制器函数在输入有效字符之前不会删除字符

更新时间:2023-11-06 21:23:16

你应该使用像这样的指令,而不是在控制器上这样做:

Instead of doing that on the Controller you should be using a Directive like this:

app.directive('restrict', function($parse) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, iElement, iAttrs, controller) {
            scope.$watch(iAttrs.ngModel, function(value) {
                if (!value) {
                    return;
                }
                $parse(iAttrs.ngModel).assign(scope, value.toLowerCase().replace(new RegExp(iAttrs.restrict, 'g'), '').replace(/\s+/g, '-'));
            });
        }
    }
});​

然后像这样在您的 input 上使用它:

And then use it on your input like this:

<input restrict="[^a-z0-9\-\s]" data-ng-model="slug" ...>

jsFiddle:http://jsfiddle.net/9qxFK/5/