1

I'm building a form using AngularJS that has groups of radio buttons. I'd like to provide my users with an accurate count of how many errors are on the form. My problem is this:

Using this code, I am keeping count of the number of errors on my form.

$scope.numberoferrors = function(form) {
  var count = 0,
  errors = form.$error;
  angular.forEach(errors, function(val) {
    if (angular.isArray(val)) {
      count += val.length;
    }
  });
  return count;
};

I make a group of two radio buttons and make each one required. If neither are selected, form.$error reports that there are two errors (one for each input), but I would expect there to be only one error. What makes this baffling is that once a radio button is selected, form.$error reports zero errors, expected.

<form name="myForm" ng-submit="submitForm()" ng-controller="ExampleController">
  Errors: {{numberoferrors(myForm)}}
  <input type="radio" ng-model="test" value="yes" required> Yes
  <input type="radio" ng-model="test" value="no" required> No
</form>

Is there a way to get a more accurate count of errors on the form?

Plunkr

Community
  • 1
  • 1
Courtney B Reid
  • 156
  • 1
  • 10

1 Answers1

0

You can give each input field a name="..." attribute and then access each field's $error: formName.fieldName.$error

You can loop over the properties of the form in order to check them all.

Any excerpt from one of the examples from the Angular form guide:

<form name="form" class="css-form" novalidate>
    Name:
    <input type="text" ng-model="user.name" name="uName" required="" />
    <br />
    <div ng-show="form.$submitted || form.uName.$touched">
      <div ng-show="form.uName.$error.required">Tell us your name.</div>
    </div>

As you can see, they make use of form.uName.$error

https://docs.angularjs.org/guide/forms

Itamar L.
  • 519
  • 2
  • 8