gpt4 book ai didi

angularjs - 在 Angular 中重用验证条件

转载 作者:行者123 更新时间:2023-12-04 05:16:30 24 4
gpt4 key购买 nike

我喜欢 Angular 的表单验证状态的粒度,但是当您有一个包含很多字段的表单时,它会变得有点笨拙——即使是两个字段也会开始让您的标记变得有点湿漉漉的。采用以下示例片段:

<form novalidate name="myForm" ng-submit="myForm.$valid && vm.submit()">
<div>
<input type="text" required id="username" name="username" ng-model="vm.username" />
<div ng-show="(myForm.username.$touched || myForm.$submitted) && myForm.username.$invalid">
<!--various validation messages here-->
</div>
</div>
<div>
<input type="email" required id="email" name="email" ng-model="vm.email" />
<div ng-show="(myForm.email.$touched || myForm.$submitted) && myForm.email.$invalid">
<!--various validation messages here-->
</div>
</div>
</form>

有没有办法做更像下面的事情?

<form novalidate name="myForm" ng-submit="myForm.$valid && vm.submit()">
<div>
<input type="text" required id="username" name="username" ng-model="vm.username" />
<div ng-show="shouldShowValidationMessagesFor(myForm.username)">
<!--various validation messages here-->
</div>
</div>
<div>
<input type="email" required id="email" name="email" ng-model="vm.email" />
<div ng-show="shouldShowValidationMessagesFor(myForm.email)">
<!--various validation messages here-->
</div>
</div>
</form>

最佳答案

如何按照您的建议在您的 Controller 中创建一个方法:

$scope.shouldShowValidationMessagesFor = function (field) {
var form = $scope.myForm;
return (form[field].$touched || form.$submitted) && form[field].$invalid;
};

在你看来,只要按照上面的逻辑,传入你需要验证的字段名就可以了。

<form novalidate name="myForm" ng-submit="myForm.$valid && vm.submit()">
<div>
<input type="text" required id="username" name="username" ng-model="vm.username" />
<div ng-show="shouldShowValidationMessagesFor('username')">
<!--various validation messages here-->
</div>
</div>
<div>
<input type="email" required id="email" name="email" ng-model="vm.email" />
<div ng-show="shouldShowValidationMessagesFor('email')">
<!--various validation messages here-->
</div>
</div>
</form>

关于angularjs - 在 Angular 中重用验证条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29356786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com