I have created a JSFiddle of the issue I am experiencing here: /
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
I have created a JSFiddle of the issue I am experiencing here: http://jsfiddle/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
Share Improve this question edited Feb 4, 2013 at 1:33 Pavel Hlobil 1,7821 gold badge15 silver badges23 bronze badges asked Dec 18, 2012 at 12:15 Sc0ttyDSc0ttyD 1,7562 gold badges16 silver badges22 bronze badges1 Answer
Reset to default 16Instead 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/9qxFK/5/