Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 760
Sc0ttyD Avatar asked Dec 18 '12 12:12

Sc0ttyD


1 Answers

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/

like image 70
bmleite Avatar answered Oct 31 '22 18:10

bmleite