javascript - 如何判断 Angular 形式自定义指令无效

标签 javascript angularjs

我有自定义 Angular Directive(指令):

<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 字段才能更改它。 当内部指令无效字段为真时,我应该添加什么以使表单无效?

最佳答案

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

关于javascript - 如何判断 Angular 形式自定义指令无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40992312/

相关文章:

css - 在 mouseenter 上以 Angular 更改 CSS

javascript - HTML CSS JS 缩小架构

javascript - 如何获取变量的值?

javascript - 将字符串转换为 javascript 关联数组

javascript - 使用ajax开发登录页面失败

javascript - Ajax 未使用 Jasmine 执行

通过 href 调用 javascript 函数?

javascript - $location.path 重定向到错误的位置

angularjs - Bootstrap 3.0 应用程序不滚动

javascript - AngularJS 从指令更新作用域变量