1

I have a modal with two input fields and I'm trying to give an ng-class to the form-group if $invalid on submit.

For that, I'm doing:

<div class="form-group" ng-class="{ 'has-error': item.answer[field2].$invalid }">
    <label>{% verbatim %}{{ model.structure.field2 }}{% endverbatim %}</label>
    <textarea name="answer[field2]" class="form-control"
              ng-model="model.answer.field2" ng-required="true">
     </textarea>
</div>

Keeping in mind that I need to keep the name answer[field2] unless it's the only way, is there a workaround for the brackets?

Also tried answer[field2].$invalid, item.answer[field2].$invalid and item.answer.field2.$invalid, but din't work.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Ryuuks
  • 380
  • 2
  • 18
  • 1
    Let's say that the wrapping form is something like `
    ` then it should work using `ng-class="{ 'has-error': myForm.answer[field2].$invalid }"`
    – Alon Eitan Mar 20 '19 at 13:51
  • @AlonEitan it should and I'm doing the same with other twig templates (no brackets there) and they work fine – Ryuuks Mar 20 '19 at 14:02
  • And just to be sure - The class is NOT added? Is it possible that the class itself is being added but there's no specific style for it? – Alon Eitan Mar 20 '19 at 14:04
  • 1
    Good point, but no, the class is not added – Ryuuks Mar 20 '19 at 14:11
  • Sorry, i'm out of ideas then. Hope you'll get your answer soon enough – Alon Eitan Mar 20 '19 at 14:12
  • Thank you for trying :) – Ryuuks Mar 20 '19 at 14:13
  • When asking a question about a problem caused by your code, you will get much better answers if you provide code people can use to reproduce the problem. That code should be… **Complete** – Provide all parts needed to reproduce the problem *in the question itself.* – georgeawg Mar 20 '19 at 15:14
  • Is `$scope.item.answer` an object or an array? Is `$scope.field2` a number or a string? Why did you name the form `item`? That's a bit strange. – georgeawg Mar 20 '19 at 15:29
  • @georgeawg It's an object and a string, but I already figured it out (and answered it myself). About the name, was just an easier word to use as example for the question. Thank you for the suggestions. – Ryuuks Mar 20 '19 at 17:18

1 Answers1

0

I found that when comes to a name containing brackets, brackets notation is the way to go:

item['answer[field2]'].$invalid

Ryuuks
  • 380
  • 2
  • 18