angular.element versus $document[0].getElementById in a Widget's client script area?

xiaix
Tera Guru
var htmlElement = false;
htmlElement = angular.element('#my-special-button');
htmlElement = $document[0].getElementById("my-special-button");

They both get the job done, but which is best practice to use in a Widget's client script area?

4 REPLIES 4

T_Fesenko
Tera Contributor

Not sure if there's any best practice here... why would you need to get the elements? If you want to manipulate it's styles or attributes it's better to use dynamic values in HTML or CSS. 

If you're intending to do DOM manipulation - then it'd be a bad practice in both cases

xiaix
Tera Guru

Well, one thing I realized is this:

var HTML_ELEMENT = $document[0].getElementById("my-id");
if (HTML_ELEMENT) {
	HTML_ELEMENT.onfocus = function () { $scope.someOtherFunction(this); };
}

works, but this:

var HTML_ELEMENT = angular.element("#my-id");
if (HTML_ELEMENT) {
	HTML_ELEMENT.onfocus = function () { $scope.someOtherFunction(this); };
}

does not.

Keyword "this" doesn't pass the same way.  I guess I'm sticking to $document[0]

T_Fesenko
Tera Contributor

if you'd like to run some function on focus, try using the angularJS ngFocus: AngularJS: API: ngFocus

In general, I highly recommend always checking if there's a angularJS directive for what you're trying to achieve, they are really helpful 🙂 

Please mark my reply as helpful if it was. Thank you

DrewW
Mega Sage
Mega Sage

My understanding is that the angular way means you have access to the angular methods that where built.  Example would be you would use attr() to set an attribute instead of setAttribute().