Fine-grained error messages in Angular Dart forms

2019-07-21 08:09发布

问题:

I have the following form with some simple validation rules:

<form name="signup_form" novalidate ng-submit="ctrl.signupForm()">
  <div class="row">
    <input placeholder="Username"
        name="username"
        ng-model="ctrl.username"
        required
        ng-minLength=3
        ng-maxLength=8>
  </div>
  <div ng-show="signup_form['username'].dirty &&
      signup_form['username'].invalid">
    <!-- ... -->
  </div>

  <button type="submit">Submit</button>
</form>

I would like to display specific error messages for required, ng-minLength and ng-maxLength, but I'm not having success being able to drill down into signup_form['username'].errors to get the specific error.

I can access the errors map just fine in the controller, it is in the markup that I cannot get a handle on the specific error. I would like to be able to do roughly something like this:

<div ng-show="signup_form['username'].errors['minlength'].invalid>
    <!-- ... -->
</div>

I.e., something like the following in angularJS:

<div ng-show="signup_form.username.$error.required">This field is required</div>

回答1:

A working example for

Inspired by this filter I tried this approach again

Angular 0.9.9

@NgFilter(name: 'errors')
class ErrorFilter {
  call(val) {
    if(val != null) {
      return val.map.keys;
    }
    return null;
  }
}

and in the markup

{{signup_form['username'].errors | errors}}

EDIT for Angular 0.9.10

@NgFilter(name: 'errors')
class ErrorFilter {
  call(val) {
    if(val != null) {
      return val.keys;
    }
    return null;
  }
}

and in the markup

{{signup_form['username'].errorStates | errors}}

I learned from the discussions I have observed in the AngularDart Github repo that better solutions are on their way.

related open issue
When this https://github.com/angular/angular.dart/pull/771 is landed
hopefully better solutions are possible.