Angularjs:验证带有或不带有表单的指令组件

Angularjs: Validating directive components with or without forms

本文关键字:指令 组件 表单 验证 Angularjs      更新时间:2023-09-26

我有一个非常简单的模态,其中包含一个文本区域和一个按钮。我为文本区域创建了一个指令,如下所示:

app.directive('vipTextArea', function() {
    return {
        restrict: 'E',
        templateUrl: 'app/common/textArea-partial.html',
        require: 'ngModel',
        scope: {
            textAreaLabel: '@',
            textAreaName: '@',
            textRequired: '@',
            iconLabel: '@',
            textAreaIcon: '@',
            formName: '@',
            value : '=ngModel'
        }
    }
});

这是模板:

<div class="col-sm-8 noPadding">
  <label>{{ textAreaLabel }}</label>
</div>
<div class="col-sm-4 noPadding rightAlign">
     <vip-button-icon button-title="{{ iconLabel }}" icon-class="{{ textAreaIcon }}"></vip-  button-icon>
</div>
<br/>
<textarea name="{{ textAreaName }}" ng-model="value" class="textAreaSize" ng-required=" {{    textRequired }}" ng-class="{ inputError: ({{ formName }}.{{ textAreaName }}.$error.required && {{ formName }}.{{ textAreaName }}.$dirty) }"></textarea>
<p class="errorMsg" ng-show="{{ formName }}.{{ textAreaName }}.$error.required && {{ formName }}.{{ textAreaName }}.$dirty">This field is required</p>

我在这里使用此指令:

<form name="viewCertificate">
<modal-header modal-title="View Certificate"></modal-header>
<div class="modal-body modalBodyHeight">
    <vip-text-area form-name="viewCertificate" text-area-name="certificate" text-area-label="Certificate text below" text-required="true" icon-label="Upload" text-area-icon="upload" ng-model="certificate"></vip-text-area>
</div>
<div class="modal-footer">
    <vip-button form-name="viewCertificate" button-title="Ok" button-size="small" button-color="blue" ng-click="ok()"></vip-button>
    <vip-button form-name="viewCertificate" button-title="Cancel" button-size="small" button-color="white" ng-click="cancel()" class="buttonMargin"></vip-button>
</div></form>

我试图实现的只是验证文本区域是否为空。我是角度的新手,所以如果我使用不正确,请纠正我。我计划使用其他指令,如自定义输入字段,因此需要为所有可能的组件提供通用解决方案。

您需要将

表单添加到指令范围,如下所示:

.directive('vipTextArea', function() {
     return {
      require: ['^form','ngModel'],
      restrict: 'E',
      templateUrl: 'app/common/textArea-partial.html',
      scope: {
        textAreaLabel: '@',
        textAreaName: '@',
        textRequired: '@',
        iconLabel: '@',
        textAreaIcon: '@',
        formName: '@',
        value : '=ngModel'
     },
     link: function(scope, elem, attrs, ctrl){
      scope.form = ctrl[0];
     }
 }

,然后使用范围表单更新您的段落:

    <p ng-show="form.{{ textAreaName }}.$invalid && form.{{ textAreaName }}.$dirty">This field is required</p>