[英]How can I manage form validity from an Angular Directive?
I have error spans on a page: 我在页面上出现错误跨度:
<span id="example" name="example" ng-model="example">
<span ng-show="form.example.$error.exampleError">
{{'example' | translate}}
</span>
</span>
I need to set the validity on this from a directive so I am passing the form as an attribute. 我需要通过指令设置有效性,因此我将表单作为属性传递。
<form name="form">
<my-directive form="form"></my-directive>
</form>
Inside the directive I then set the validity to true or false. 然后在指令内部,将有效性设置为true或false。
This works, however from a design perspective I am creating a circular dependency as I have a directive inside a form and then I am passing the form to the directive, so my question really is, is there a better way to achieve this with passing the form to the directive? 这是可行的,但是从设计的角度来看,因为我在表单中有一个指令,所以正在创建一个循环依赖项,然后将表单传递给该指令,所以我的问题确实是,是否存在一种更好的方法来通过传递指令的形式?
I could create a service that stores the state of the form (true/false) and use ng-show, but I would prefer to use $error and $setValidity. 我可以创建一个存储表单状态(真/假)并使用ng-show的服务,但是我更喜欢使用$ error和$ setValidity。
This article really helped me with this kind of scenario: 本文确实为我解决了这种情况:
http://blog.thoughtram.io/angularjs/2015/01/11/exploring-angular-1.3-validators-pipeline.html http://blog.thoughtram.io/angularjs/2015/01/11/exploring-angular-1.3-validators-pipeline.html
angular.module("app")
.directive('validateExample', function () {
return {
require: 'form',
link: function (scope, element, attrs, ctrl) {
if (you-want-example-to-be-valid) {
ctrl.$setValidity("example", true);
}else{
ctrl.$setValidity("example", false);
}
}
};
});
Then in your html you would do something like this: 然后在您的html中,您将执行以下操作:
<form name="FormName" validate-example novalidate>
<input id="example" name="example" ng-model="example"/>
</form>
<div ng-messages="FormName.$error" role="alert">
<div class="alert-danger" ng-message="example">This error will show if example is invalid according to the directive
</div>
</div>
Take note that I'm using Angular's ngMessages you can read more on it here: 请注意,我正在使用Angular的ngMessages,您可以在此处阅读更多内容:
https://scotch.io/tutorials/angularjs-form-validation-with-ngmessages https://scotch.io/tutorials/angularjs-form-validation-with-ngmessages
It depends on what your directive does. 这取决于指令的作用。 Take a look at require property for the directive - https://docs.angularjs.org/guide/directive
看一下指令的require属性-https: //docs.angularjs.org/guide/directive
One way is to use attribute directive on the form itself. 一种方法是在表单本身上使用属性指令。
angular.module('app').directive('formDirective', function() {
return {
require: 'form',
restrict: 'A',
link: function (scope, element, attrs, formCtrl) {
//do stuff with your form using formCtrl
}
};
});
Then you do 那你做
<form name="form" form-directive>
</form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.