Angular.js - controller function to filter invalid chars from input does not delete chars until a valid char is entered

后端 未结 1 2081
日久生厌
日久生厌 2021-02-09 11:55

I have created a JSFiddle of the issue I am experiencing here: http://jsfiddle.net/9qxFK/4/

I have an input field that I want to only permit lower case letters, numbers,

1条回答
  •  情书的邮戳
    2021-02-09 12:29

    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, '-'));
                });
            }
        }
    });​
    

    And then use it on your input like this:

    
    

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

    0 讨论(0)
提交回复
热议问题