带有过滤问题

时间:2016-11-14 10:08:33

标签: angularjs

我有几个输入字段,如果只是空格,我希望验证用户输入。我尝试使用指令或过滤器。我不想使用$ watch,因为输入字段太多了。我需要的是:如果用户在输入字段中只设置了一些空格,则需要一些函数或指令来清理这个空格。 我可以用jQuery或vanilla JS做到这一点,但我更喜欢这个结果是有角度的。

我在指令或过滤器中出错了

这是我的代码:

angular.module('app')
.directive('customSpaceValidation', ['$filter', function ($filter) {
    return {
        require: '?ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl.replace(/\s/g, '').length) {
                ctrl = "";
            }
            return ctrl;
        }
    };
}])
.filter('nospace', function () {
    return function (value) {
        if (!value.replace(/\s/g, '').length) {
            value = "";
        }
        return value;
    };
})

这是带指令的html:

<input type="text" class="form-control" id="inputKey" ng-model="channel.key" customSpaceValidation data-ng-trim="false" ng-required="true" name="inputKey" required />

这是带过滤器的html

<input type="text" class="form-control" id="inputKey" ng-model="channel.key | filter : nospace" data-ng-trim="false" ng-required="true" name="inputKey" required />

过滤trow例外:

ng-table-export.src.js:45 TypeError: ngModelSet is not a function
at NgModelController.$$writeModelToScope (ng-table-export.src.js:45)
at writeToModelIfNeeded (ng-table-export.src.js:45)
at ng-table-export.src.js:45
at validationDone (ng-table-export.src.js:45)
at processAsyncValidators (ng-table-export.src.js:45)
at NgModelController.$$runValidators (ng-table-export.src.js:45)
at NgModelController.$$parseAndValidate (ng-table-export.src.js:45)
at NgModelController.$commitViewValue (ng-table-export.src.js:45)
at ng-table-export.src.js:45
at Scope.$eval (ng-table-export.src.js:45)

1 个答案:

答案 0 :(得分:1)

您不能将ng-model与过滤器一起使用,因为过滤是单向操作,而ng-model是双向绑定。在HTML中使用时,该指令必须是蛇形的而不是camelCased,即custom-space-validation

要实际验证,您需要验证器:

.directive('customSpaceValidation', [function() {
    var RE = /^\s+$/;

    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, ngModel) {
            ngModel.$validators['customSpace'] = function(modelValue, viewValue) {
                var value = modelValue || viewValue;
                return !RE.test(value);
            };
        }
    };
}])