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

All we need is an easy explanation of the problem, so here it is.

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, and hyphens (this field will be used in a URL).

I have the following angular.js controller method in order to do this:

$scope.auto_slug = function() {
    $scope.slug = $scope.slug.toLowerCase().replace(/[^a-z0-9\-\s]/g, '').replace(/\s+/g, '-');
};

Invalid characters are only being removed when a valid character is typed after an invalid character.

Can anybody tell me why this doesn’t work?

Thanks, Scott

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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:

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

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

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply