0

Angular offers great possibilities for reading the status of an input field, like $dirty, $touched and so on. However, as far as I found out, that works only when accessing an input element by its name, like $scope.formName.inputFieldName.

But I need to access an input element defined in a directive template inside the directive's controller by the element's ID (and without the form name). Whatever I try, I don't get the special input form handles. Something like

var myElement = $document[0].getElementById('my_id');
console.log(angular.element(myElement));

doesn't work. I get the DOM element itself, wrapped inside generic object context, but not the input handles Angular offers.

cis
  • 1,259
  • 15
  • 48
  • 1
    Found that one here http://stackoverflow.com/questions/23609171/how-to-get-element-by-classname-or-id in Ari's answer. However, it doesn't seem to matter. Using vanilla JavaScript 'document.getElementById' gives exactly the same result. – cis May 02 '16 at 08:11
  • What are you trying to do? Have you tried the element parameter from the link function? – tdhulster May 02 '16 at 08:13
  • That doesn't exist. I generate dozens of input elements inside this directive template. And I want to access one single of them in the directive's controller function. – cis May 02 '16 at 08:16
  • 1
    Did you try `angular.element(myElement).controller("ngModel")`? – georgeawg May 02 '16 at 10:53
  • @georgeawg That did the trick! Thanks! – cis May 02 '16 at 11:20

1 Answers1

3

Use angular.element(myElement).controller("ngModel") to access the model controller of an input element.

For more information, see AngularJS element function API Reference -- jqLite Extras

georgeawg
  • 48,608
  • 13
  • 72
  • 95