0

I have built a custom angular component to select multiple elements from a collection. This custom element has an array as ngModel. I would like it to reflect the validation state, i.e : ng-invalid ng-invalid-required.

if I add in the tpl of the custom element an input field with this ngModel, the validation state is updated correctly. But if it is on the wrapping div of this custom element, it does not work:

<input type="text" ng-model="$ctrl.selected" name="selected" required /><!--WORKS-->
<div
    class="pseudoField"
    ng-model="$ctrl.selected"
    required
    name="test"
><!--NOT WORKING-->

If the form that contains that custom element gets submitted, the validation state is corrrectly reflected on the input. It gets the css classes : "ng-invalid ng-invalid-required." But the same thing does not happend on the div.

How to make this happend on the div ?

EDIT: To give some context, the component is an autocomplete-dropdown thing, that allows to select multiple element from a list presented in a dropdown. Once selected, the item gets in a list of selected items, presented like "tags". It is similar to select2 "Tagging support" example : https://select2.github.io/examples.html

To achieve that I have wrapped an input in a container div ".pseudoField". When the container div is clicked, it passes the focus to that input element. The input has its border styling removed, so it is "invisible". When the input is focused, the styling of div.pseudoField is changed to make it look like it is focused. That way, for the user the div.pseudoField acts like a form element, and I would like it to also have the validation state. Hope that makes sense.

Olivvv
  • 1,140
  • 1
  • 13
  • 37

1 Answers1

1

You can't use ng-model on a <div>. From the ng-model docs:

The ngModel directive binds an input, select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.

Mistalis
  • 17,793
  • 13
  • 73
  • 97
  • Then would it be possible to put the ngmodel on an display: none input field and copy its validation state ? – Olivvv Mar 27 '17 at 14:52
  • @Olivvv It seems a bit snicky, I don't understand why you want to do that. What you are trying to achieve? – Mistalis Mar 27 '17 at 14:53
  • I edited the question the explain what I am trying to achieve. – Olivvv Mar 27 '17 at 15:03
  • BTW, I think "custom form control" means that it should work for divs too. That is the obvious way to do a contenteditable : https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#custom-control-example – Olivvv Mar 27 '17 at 16:03