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
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With