angular.element vs document.getElementById or jQuery selector with spin (busy) control

irascian picture irascian · Jun 21, 2013 · Viewed 557k times · Source

I'm using the "Angularised" version of the Spin control, as documented here: http://blog.xvitcoder.com/adding-a-weel-progress-indicator-to-your-angularjs-application/

One of the things I don't like about the shown solution is the use of jQuery in the service that effectively attaches the spin control to the DOM element. I would prefer to use angular constructs to access the element. I'd also like to avoid "hard-coding" the id of the element that the spinner needs to attach to within the service and instead use a directive that sets the id in the service (singleton) so that other users of the service or the service itself don't need to know that.

I'm struggling with what angular.element gives us vs what document.getElementById on the same element id gives us. eg. This works:

  var target = document.getElementById('appBusyIndicator');

None of these do:

  var target = angular.element('#appBusyIndicator');
  var target = angular.element('appBusyIndicator');

I'm clearly doing something that should be fairly obvious wrong! Can any one help?

Assuming I can get the above working, I have a similar problem with trying to replace jQuery access to the element: eg $(target).fadeIn('fast'); works angular.element('#appBusyIndicator').fadeIn('fast') or angular.element('appBusyIndicator').fadeIn('fast') doesn't

Can someone point me to a good example of documentation that clarifies use of an Angular "element" vs the DOM element? Angular obviously "wraps" the element with its own properties, methods etc but it's often hard to get the original value. For example if I have an <input type='number'> field and I want to access the original contents that are visible in the ui when the user types "--" (without the quotes) I get nothing, presumably because the "type=number" means Angular is rejecting the input even though it's visible in the UI and I want to see it so I can test for it and clear it down.

Any pointers/answers appreciated.

Thanks.

Answer

kaiser picture kaiser · Sep 20, 2013

It can work like that:

var myElement = angular.element( document.querySelector( '#some-id' ) );

You wrap the Document.querySelector() native Javascript call into the angular.element() call. So you always get the element in a jqLite or jQuery object, depending whether or not jQuery is available/loaded.

Official documentation for angular.element:

If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angulars built-in subset of jQuery, that called "jQuery lite" or jqLite.

All element references in Angular are always wrapped with jQuery or jqLite (such as the element argument in a directives compile or link function). They are never raw DOM references.

In case you do wonder why to use document.querySelector(), please read this answer.