dabeige dabeige - 2 years ago 286
Javascript Question

Can I get an html element content using angular by angular.element(document.getElementById('id')).html(); because the console show a object undefined

I am trying to get an element content in angular controller, and I have read some questions about angular element.so since I use the angular element and element method, how come the console shows an object undefined.and whatever i use jquery or angular element, the result are both undefined.

enter image description here

enter image description here

Answer Source

You are mixing different approaches for finding element in one query.

1) document.getElementById("elem_id")

will return a DOM element itself.After that you can call angular.element() or $() passing inside your found element. The id of an element must be globally unique in case to work only with one and the same element each time you want to access it by id

2) angular.element() and $() are the same operations because angular has built in jquery "support". If you are using jQuery and loading it BEFORE you you are loading angular on your page angular will use it inside, in other case angular will work with its own engine called jqLite

3) According to previos point, you can use angular directly to work with you DOM elements because it supports all possible selectors as it does jQuery. So you can find your element with angular by angular.element("elem_id/css_class_name/any_css_selector") and work with it. So if you want to call html() method on your element you can do it as angular.element("elem_id").html(). Boom, it works!!!

In your code, you are first trying to find an element with document and I think it does, then as a selector you a passing your found element to angular.element() method. That's why it can not found nothin => undefined result

P.S. As a suggestion do not mix jQuery code with your angular code. This is absolutely semantically incorrect and wrong!!!. If you need jQuery, let's say for bootstrap framework - ok, include it into your page. But if you are writing an Angular application - work only with angular as a main application code. As wrote previosly, angular can do exact the same work as it can do jQuery. Moreover, Angular can do more work than jQuery - just explore it :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download