如何判断角度形式自定义指令无效

2023-12-23

我有自定义角度指令:

<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>

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


您可以使用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"
    };
});

这样,角度将包括验证错误到它的$invalid财产和$errors (myForm.myFieldName.$errors.timeString)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何判断角度形式自定义指令无效 的相关文章

随机推荐