Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: How to get a DOM element by id

Sample

Please consider this Plunkr.

What I need

I need to be able to get an element by it's id.

The sample code should be able to assign a css class to any DOM element that exists on the current view.

This should be checked using a source object, provided by the $scope in a controller. This source object may/will have more properties than there are input elements on the view.

So I want to loop through each object key and see if a corresponding DOM element exists. If so, validate it's value.

The question

How do I get an element by id, using AngularJS only (jQuery is NOT allowed!!)?

Specifically for the Plunkr, I need this function to (really) work:

self.IsFieldCurrentlyActive = function(field){
  // Should be (in pseudocode):
  // var inputElement = angular.find(field);
  // return (inputElement != 'undefined');

  // Sample only
  var idx = field.indexOf('Unused');
  return idx == -1;
};

And this one (basically the same):

self.GetElementByKey = function(key)
{
  // Should be (in pseudocode):
  // var inputElement = angular.find(field);
  // return inputElement;

  // Sample only
  return null;
}

Update

Apologies, I forgot to add an important requirement: I can't use any mechanism that assumes unique IDs, because there may be multiple occurrences of the same form (and the same IDs). So, I need to respect the Angular scope.

Thanks!

like image 780
Spikee Avatar asked Sep 09 '15 10:09

Spikee


2 Answers

In pure JS you can do document.querySelector('#myID');

Or within angular using angular.element: angular.element(document.querySelector('#myID'));

like image 108
Lauromine Avatar answered Oct 17 '22 00:10

Lauromine


Instead try angular.element($('#myElement'));

like image 1
Nishith Kant Chaturvedi Avatar answered Oct 17 '22 01:10

Nishith Kant Chaturvedi