Angular自定义验证器导致范围变量未定义?

时间:2015-09-06 01:29:39

标签: javascript angularjs validation

我正在为一个检查数组长度的指令实现一个自定义验证器,但是当我尝试在验证器中取消注释其中一行代码时,我遇到了一个有趣的问题:

angular.module("directives.tags", []).directive("tags", ["Tag", "$timeout", function(Tag, $timeout) {
    return {
        require: 'ngModel',
        restrict: 'E',
        scope: {
            availableTags: '=',
            currentTags: '=ngModel'
        },
        link: function($scope, element, attributes, ctrl) {

            // Snip

            $scope.updateSuggestionList = function() {
                var search = new RegExp($scope.tagInput, "i");

                $scope.suggestions = $scope.availableTags.filter(function(availableTag) {
                    if ($scope.currentTags.filter(function(currentTag) {
                            return availableTag.name == currentTag.name;
                        }).length == 0) {
                        return search.test(availableTag.name);
                    }
                    return false;
                }).slice(0,6);
            };

            // PROBLEM APPEARS TO BE HERE
            ctrl.$validators.taglength = function(currentTags) {
                return true; // <-- This works just fine
                return currentTags.length > 0 && currentTags.length < 6; // <-- This does not work at all
            };

            $scope.$watch('currentTags', function() {
                ctrl.$validate();
            }, true);

        },
        templateUrl: // snip
    }
}]);

当我尝试使用这一行:return currentTags.length > 0 && currentTags.length < 6;时,当currentTags.length应为0时,它返回undefined:

Error: $scope.currentTags is undefined
.link/$scope.updateSuggestionList/$scope.suggestions<@http://localhost:3000/js/app.js:1116:1
.link/$scope.updateSuggestionList@http://localhost:3000/js/app.js:1115:38
anonymous/fn@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js line 13231 > Function:2:248
ngEventHandler/</callback@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:23411:17
$RootScopeProvider/this.$get</Scope.prototype.$eval@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:15916:16
$RootScopeProvider/this.$get</Scope.prototype.$apply@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:16016:20
ngEventHandler/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:23416:17
n.event.dispatch@https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js:3:6414
n.event.add/r.handle@https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js:3:3224

然而,如果我评论该行并简单地返回true或false。它虽然没有经过适当的验证,但效果很好。

这是我的指令模板:

<div class="tagger-container">
    <div class="wrapper" ng-class="{ 'active': areSuggestionsVisible }">
        <div class="tag-wrapper">
            <div class="tag" ng-repeat="tag in currentTags">
                [[ tag.name ]]
                <span class="remove" ng-click="removeTag(tag)"></span>
            </div>
        </div>
        <input type="text" class="tag-input"
               ng-model="tagInput"
               ng-style="{ width: inputLength + 'px'}"
               ng-keydown="tagInputKeydown($event)"
               ng-keyup="updateSuggestionList()"
               ng-focus="toggleSuggestionVisibility()"
               ng-blur="toggleSuggestionVisibility()" />
    </div>
    <div class="suggestions" ng-show="areSuggestionsVisible">
        <div class="suggestion" ng-repeat="tag in suggestions" ng-mousedown="createTag(tag.name)">[[ tag.name ]] </div>
    </div>
</div>

以下是我的指令的称呼方式:

<tags available-tags="data.tags" name="tags" ng-model="text.tags"></tags>

data.tags示例:

[{ name: 'aTag', description: null, id: 1}, ..., ...]

1 个答案:

答案 0 :(得分:0)

解决。在$validate()的文档中:

  

运行每个已注册的验证器(第一个同步验证器,然后运行异步验证器)。如果有效性更改为无效,则模型将设置为undefined,除非ngModelOptions.allowInvalid为true。

所以我只需要设置ngModelOptions.allowInvalid = true;