将模型传递给自定义角度指令以进行验证

时间:2015-07-22 04:29:29

标签: javascript angularjs

我已经创建了一个小的angularjs指令,用于替换我页面上的验证错误

这是代码

.directive('validationErrors', function() {
        return {
            templateUrl: '/Content/biz/templates/common/validation-errors.html',
            replace: true,
            restrict: 'E',
            scope: {
                modelToValidate: '=',
                modelMinLength: '=',
                modelMaxLength: '=',
                modelPattern: '='
            }
        }
    });

它的模板

<div class="col-sm-5 pull-right" data-ng-show="modelToValidate.$dirty && modelToValidate.$invalid">
<span class="label label-warning" data-ng-show="modelToValidate.$error.required">This field is required!</span>
<span class="label label-warning" data-ng-show="modelToValidate.$error.minlength">Minimum field length should be  {{modelMinLength}}</span>
<span class="label label-warning" data-ng-show="modelToValidate.$error.maxlength">Maximum field length should be  {{modelMaxLength}}</span>
<span class="label label-warning" data-ng-show="modelToValidate.$error.pattern">Model should have {{modelPattern}}</span>

比我将它绑定到模型

 <div class="col-sm-4">
                            <input class="form-control" ng-model="data.Main.FullName" ng-maxlength="1000" required/>

                                                             

这会生成像这样的标记

<div class="col-sm-4">
                            <input class="form-control ng-valid-maxlength ng-dirty ng-valid-parse ng-invalid ng-invalid-required ng-touched" ng-model="data.Main.FullName" ng-maxlength="1000" required="">
                            <div class="col-sm-5 pull-right ng-isolate-scope" model-to-validate="data.Main.FullName" model-max-length="1000">
<span class="label label-warning ng-hide" data-ng-show="modelToValidate.$error.required">This field is required!</span>
<span class="label label-warning ng-binding ng-hide" data-ng-show="modelToValidate.$error.minlength">Minimum field length should be </span>
<span class="label label-warning ng-binding ng-hide" data-ng-show="modelToValidate.$error.maxlength">Maximum field length should be 1000</span>
<span class="label label-warning ng-binding ng-hide" data-ng-show="modelToValidate.$error.pattern">Model should have </span>

                            

但如果绑定模型有错误,则无法显示任何内容。请帮我理解为什么会这样。

1 个答案:

答案 0 :(得分:1)

我认为您需要传递给您的表单是一个ngModelController实例,而您传递的是一个模型实例。

首先将输入更改为具有名称属性

<input name="fullName" class="form-control" ng-model="data.Main.FullName" ng-maxlength="1000" required/> (还要确保您的表单具有name属性,假设它是myForm

然后指令参数应为

<div model-to-validate="myForm.FullName" model-max-length="1000">

现在应该可以了。请记住,您使用的所有属性(如$error)都是在NgModelController实例上定义的,而不是在模型上。

您正在做的事情也可以使用ngMessage

在Angular 1.4中完成