我的页面上有错误跨度:
<span id="example" name="example" ng-model="example">
<span ng-show="form.example.$error.exampleError">
{{'example' | translate}}
</span>
</span>
我需要通过指令设置其有效性,因此我将表单作为属性传递。
<form name="form">
<my-directive form="form"></my-directive>
</form>
然后,我在指令内将有效性设置为 true 或 false。
这是可行的,但是从设计的 Angular 来看,我正在创建循环依赖关系,因为我在表单内有一个指令,然后我将表单传递给指令,所以我的问题确实是,有没有更好的方法来实现这一点将表单传递给指令?
我可以创建一个存储表单状态(true/false)的服务并使用 ng-show,但我更喜欢使用 $error 和 $setValidity。
最佳答案
这篇文章确实帮助我解决了这种情况:
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);
}
}
};
});
然后在你的 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>
请注意,我正在使用 Angular 的 ngMessages,您可以在此处阅读更多信息:
https://scotch.io/tutorials/angularjs-form-validation-with-ngmessages
关于javascript - 如何通过 Angular 指令管理表单有效性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35969681/