最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular.js - controller function to filter invalid chars from input does not delete chars until a valid char is ent

programmeradmin2浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 16

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/9qxFK/5/

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论