角度验证指令

时间:2015-09-02 06:42:08

标签: angularjs validation angularjs-directive

我的应用程序中有很多表单,每个输入都有不同的验证。 我想对所有输入使用指令来显示验证错误消息,并指示用户输入无效。

最好的通用方法是什么?

1 个答案:

答案 0 :(得分:0)

您可以编写一个监视form.$error并显示所有错误的指令。

return {
    require: '^form',
    templateUrl: '...',
    link: function (scope, elem, attr, ngForm) {
        scope.$watch(
            function() { return ngForm.$error; },
            function(errors) {
                // for each error typ
                angular.forEach(errors, function(errorTypes, errorType) {
                    // for each error
                    angular.forEach(errorTypes, function(error) {
                        // handle the error

                    });
                });

        }, true);
    }
}

在表单

中使用此指令
<form novalidate>
  <my-validation></my-validation>
  <input ng-model="m" required>
</form>