0
votes

I have a lot of forms in my application, with different validation for every input. I want to use a directive for all inputs to show the validation error message, and indicate the user that the input is not valid.

What is the best generic way to do it?

1

1 Answers

0
votes

You can write a directive that watches form.$error and display all the errors.

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);
    }
}

Use this directive once inside a form

<form novalidate>
  <my-validation></my-validation>
  <input ng-model="m" required>
</form>