https://docs.angularjs.org/api/ng/type/form.FormController
将表单验证添加到bootstrap项目时,我发现自己编写了很多这样的模式:
ShareName = oParameters(0)
我试图弄清楚是否有一种简单的方法可以将新属性添加到表单控制器的元素中,例如:
<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>
我可以为此创建一个函数,但它并不是一个非常合适的解决方案来编写 myForm.email.$showError = myForm.email.$invalid && (myForm.$submitted || myForm.email.$touched
但是在查看FormController的源代码后可能会更容易
答案 0 :(得分:0)
我无法在此专门重新创建代码,但查看角形式对象的最佳方法是将其附加到父作用域对象。
在父控制器中定义:
$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>