how to access $error from nested forms

angularjs

Solution

Ok, I wasn't 100% sure I understood your question, but I think I do, so here's a stab at it:

There are a couple ways to access the errors of a child form, but all seem to need the name of the `ngForm`.

Assuming this structure:

<form name="parentForm">
  <ng-form name="childForm"></ng-form>
</form>

you know that you can access it via `$scope.childForm.$error`, but less known is that it is also attached to the parent form. You can access it with `$scope.parentForm.childForm.$error`, but obviously, that's no good, since you still need the name.

You could get hacky and loop through the properties on the parent form and try to tell which one is the child form and go from there.

Lastly, as we've discussed on Twitter/GitHub, I have a directive that kinda does some of this magic for you. It did have a bug that didn't handle embedded forms correctly, but I fixed it. Check out the new version of my directive that tries to simplify handling errors with Angular:

https://github.com/CWSpear/angular-form-errors-directive

I added the ability to display all the errors of all the child `ngForms` with a flag in `v1.3.0`.

Problem

I have one main form and another `subForm`. How I can access `$error` of the child form but without having to directly reference the subForm name? I want to be able to display that `name is required`(for example) instead of just knowing the name of the form. Here's a demo of my problem: http://plnkr.co/edit/QWZArI1UFPpJdjoK8eVn?p=preview

Original source