Skip to content Skip to sidebar Skip to footer

Angular.js - Controller Function To Filter Invalid Chars From Input Does Not Delete Chars Until A Valid Char Is Entered

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 hyphen

Solution 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/

Post a Comment for "Angular.js - Controller Function To Filter Invalid Chars From Input Does Not Delete Chars Until A Valid Char Is Entered"