0

I'm using Angular 1.5.9

I have a big form, which I scattered through different Bootstrap Accordion.

When there is an error in the form, I want to be able to change the class of my accordions to show in which accordions the error is located.

To check for errors in a whole form, I can check

myFormName.$error

And to check errors for an element, I can simply do

myFormName.myInputName.$error

But I don't know if there is a way to do this for multiple element at once, without having to check each element individually.

My first thought was to change the name of my inputs like so:

<input name="accordion1.fieldName">

But this didn't give me the expected result: I don't have myFormName.accordion1.$error, actually, I don't even have myFormName.accordion1.fieldName, since my data is actually stored in myFormName['accordion1.fieldName'] which is pretty much useless.

Has anyone found an answer to this problem? I think I'll have to check each field, which is kinda ugly, and a mess to maintain whenever we add / remove fields...

Maybe there is a directive out there that could do that for me, but as a non-native English speaker, I can't find which key words to use for my search in this situation.

2 Answers 2

2

One approach is to nest with the ng-form directive:

<form name=form1>
    <div ng-form=set1>
       <input name=input1 />
       <input name=input2 />
    </div>
</form>

{{form1.set1.$error}}
Sign up to request clarification or add additional context in comments.

Comments

0

You could name the fields with a prefix such as 'accordion1_' then add a controller function that will filter your fields.

ctrl.fieldGroup = function(form, fieldPrefix) {

    var fieldGroup = {};

    angular.forEach(form, function(value, key) {

        if (key.indexOf(prefix) === 0) {
            fieldGroup[key] = value;
        }

    });

    return fieldGroup;

}

Then ctrl.fieldGroup('accordion1') will return an object with the appriopriate fields on it. You could extend the function further to add an aggregate $error property to the resulting fieldGroup object.

1 Comment

That's what I would have gone for if I had no better solution, but with @georgeawg's solution, I won't have to add any code in my controllers, so I'll probably go for his method ^^'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.