gpt4 book ai didi

javascript - 向 Angular 的 FormController 添加属性

转载 作者:行者123 更新时间:2023-11-28 06:35:05 25 4
gpt4 key购买 nike

https://docs.angularjs.org/api/ng/type/form.FormController

当向引导项目添加表单验证时,我发现自己经常编写此模式:

<form name="myForm">
<div class="form-group"
ng-class="{ 'has-error' : myForm.email.$invalid && (myForm.$submitted || myForm.email.$touched) }">
<label>Email*</label>
<input type="email"
class="form-control"
name="email"
ng-model="checkout.info.customer_email"
required />

<div class="help-block"
ng-show="myForm.email.$invalid && (myForm.$submitted || myForm.email.$touched)">
<div ng-show="myForm.email.$error.required">This field is required.</div>
<div ng-show="myForm.email.$error.email">This email address is not properly formatted.</div>
</div>
</div>
</form>

我试图弄清楚是否有一种简单的方法可以向表单 Controller 的元素添加新属性,例如:

 myForm.email.$showError = myForm.email.$invalid && (myForm.$submitted || myForm.email.$touched

我可以为此创建一个函数,但感觉不是必须编写 showError(myForm, myForm.email) 的正确解决方案,但也许在查看之后会容易得多查看 FormController 的源代码

最佳答案

我无法在此处专门重新创建您的代码,但查看 Angular 表单对象的最佳方法是将其附加到父范围对象。

在父 Controller 中定义:

            $scope.myFormScope = {};
$scope.myFormScope.showError = function() {
if(!!$scope.myFormScope.myForm) {
return $scope.myFormScope.myForm.email.$invalid &&
($scope.myFormScope.myForm.$submitted || $scope.myFormScope.myForm.email.$touched);
}
}

然后这是标记的样子

         <form name="myFormScope.myForm">
<div class="form-group"
ng-class="{ 'has-error' : myFormScope.showError() }">
<label>Email*</label>
<input type="email"
class="form-control"
name="email"
ng-model="checkout.info.customer_email"
required />

<div class="help-block" ng-show="myFormScope.showError()">
<div ng-show="myFormScope.myForm.email.$error.required">This field is required.</div>
<div ng-show="myFormScope.myForm.email.$error.email">This email address is not properly formatted.</div>
</div>
</div>
<input type="submit" />
</form>

关于javascript - 向 Angular 的 FormController 添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34364547/

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