【问题标题】:How to tell angular form custom directive is invalid如何判断角度形式的自定义指令无效
【发布时间】:2016-12-06 09:48:17
【问题描述】:

我有自定义角度指令:

<div class="input-group" name="name" ng-class="{ 'has-error has-feedback' : invalid }">
    <span class="input-group-addon"><i class="fa fa-paw"></i>&nbsp;{{label}}</span>
    <input type="text" class="form-control input-lg" ng-model="ngModel" ui-mask="99.99.9999" ui-mask-placeholder ui-mask-placeholder-char="-" model-view-value="true" placeholder="mm.dd.yyyy" ng-required="required" />
    <span ng-show="invalid" class="form-control-feedback" aria-hidden="true"><i class="fa fa-paw"></i></span>
</div>

指令初始化代码:

.directive("smth", function($rootScope) {
    var link = function(scope, element, attrs) {
        scope.invalid = false;
        scope.$watch("ngModel", function(value) {
            if(scope.ngModel) {
                scope.invalid = !$rootScope.timeStringValid(scope.ngModel);                }
            else {
                scope.invalid = false;
            }
        });
    };
    return {
        restrict: "E",
        scope: {
            name: "=name",
            label: "=label",
            ngModel: "=",
            required: "=required"
        },
        link: link,
        templateUrl: "smth.html"
    };
})

表单内指令的使用:

                <form class="form-horizontal" name="smthForm">
                    <div class="row">...</div>
                    <smth label="'Birth date'" ng-model="data.birthdate" type="birthdate" required="true"></smth>
                </form>

当指令输入无效时,它的外观会按预期改变。但是,包含指令的表单对其有效性状态一无所知,我无法弄清楚如何使其手动工作。另一方面,表单以某种方式知道输入何时为空并变为无效(“必需”参数有效)。 我尝试了几种基于 $setValidity("smth", !scope.invalid) 的方法,但都失败了,基本上我无法理解我的自定义指令中必须有哪些确切的实体具有 $invalid 字段才能更改它。 当内部指令无效字段为真时,我应该添加什么才能使表单无效?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    您可以使用ngModel 验证器:

    .directive("smth", function($rootScope) {
        var link = function(scope, element, attrs, ngModelCtrl) {
    
            // Add custom validator
            ngModelCtrl.$validators["timeString"] = function(modelValue) {
                return !$rootScope.timeStringValid(modelValue);
            }
        };
        return {
            restrict: "E",
            scope: {
                name: "=name",
                label: "=label",
                ngModel: "=",
                required: "=required"
            },
            // require ngModel controller
            require: "ngModel",
            link: link,
            templateUrl: "smth.html"
        };
    });
    

    这种方式 Angular 会将验证错误包含在其 $invalid 属性和 $errors (myForm.myFieldName.$errors.timeString) 中

    【讨论】:

    • 谢谢!我的主要问题是没有“require:”ngModel”,返回对象导致我的ngModelCtrl未定义。这个添加真的很难理解,你节省了我很多时间。
    猜你喜欢
    • 1970-01-01
    • 2011-06-01
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多