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

I created a JSFiddle problem that I am experiencing here: http://jsfiddle.net/9qxFK/4/

I have an input field that I want to allow only for letters, numbers and hyphens in lower case (this field will be used in the URL).

For this, I use the following angular.js method:

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

Invalid characters are deleted only after entering a valid character after an invalid character.

Can someone tell me why this is not working?

Thanks Scott

+7
source share
1 answer

Instead of doing this on the controller, you should use 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 input as follows:

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

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

+16
source

All Articles