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>


我试图找出是否有一种简单的方法可以向表单控制器的元素添加新属性,例如:

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


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

最佳答案

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

在父控制器中定义以下内容:

            $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>

08-17 13:45