Angularjs:验证带有或不带有表单的指令组件
Angularjs: Validating directive components with or without forms
我有一个非常简单的模态,其中包含一个文本区域和一个按钮。我为文本区域创建了一个指令,如下所示:
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>
相关文章:
- 如何在另一个组件中获取指令/组件实例
- 过早运行的角度组件/指令的$postLink
- 使用PrimeNG组件时出现问题(未找到指令注释)
- 不允许使用引导清单'组件'指令
- AngularJS'不可知论者;和'组件'指令
- 如何将多个指令添加到单个组件中
- 组件类型角度指令 ng 模板
- AngularJS,从指令迁移到组件
- Angularjs:验证带有或不带有表单的指令组件
- 角度 1.5 中的组件和指令
- Angular的指令作为Web组件 - 为什么需要up
- 在 Ionic 2 中,如何创建使用 Ionic 组件的自定义指令
- 如何将 angularJS 指令/组件作为属性传递给其他指令/组件
- AngularJS 2:如何拥有一个'属性'指令与其主机组件通信
- AngularJs-为什么像Angular strap和UI Bootstrap这样的指令使用提供者来构建他们的组件
- 扩展时钟组件的角度指令以单独显示日期时间元素
- 切换组件不能在跨包指令上工作
- AngularJS指令ngOpen可以用于手风琴组件吗?
- AngularJS:将ng模型从指令组件传递到控制器
- Angular 2 -根据页面切换指令组件