toggle menu

[AngularJS] AngularJS 안의 작은 jQuery - angular.element()

2012. 11. 24. 16:53 AngularJS
들어가며


angular.element() API는 DOM Element나 HTML String을 jQuery Element로 바꿔주는 API다.

angular.element 로 감싼 Element는 jQuery 가 로드되어 있다면 바로 jQuery API를 실행할 수 있으며, jQuery가 없더라도 jqLite에 포함된 약 30여개의 jQuery 호환 API를 실행할 수 있다. jqLite는 매우 작은 jQuery 호환 API 집합으로, 앵귤러가 DOM을 조작할 수 있게 해준다고 보면 된다.




jQuery 와 jqLite


DOMContentLoaded 이벤트가 실행되기 전에 로드된 진짜 jQuery는 항상 jqLite보다 우선한다.

반대로, AngularJS가 jQuery 라이브러리보다 먼저 로드되었다면, AngularJS에 내장된 jqLite가 우선되어 jQuery API를 사용할 수 없게 된다. 따라서 AngularJS와 JQuery를 함께 사용하고 싶다면, jQuery 를 AngularJS보다 먼저 로드되도록 해야한다.


angular.element("#elementId").text("Hello world");


이런식으로 angular.element 안에서 jQuery 식 셀럭터를 사용하고 싶다면, 라이브러리 로드 순서를 AngularJS보다 jQuery가 먼저 되도록 HTML 파일 상에서 처리해줄 필요가 있다.



DOM Selector 가 빠진 jqLite

DOM Element를 Selecting 하기위한 목적으로 jQuery를 사용할 때가 많은데, jqLite에는 이 DOM Selecting 기능이 없기 때문에, 만약 jQuery 라이브러리없이 작업하려면,

angular.element(document.querySelector('#elementId')).text("Hello world");
angular.element(document.getElementById('elementId')).text("Hello world");


위와 같이 querySelector 나 getElementById 등을 사용해서 Selecting을 해야 한다.



한가지 주의할 점은, 앵귤러 상의 모든 element 참조들은 jQuery로 랩핑되어 있다는 점이다. 단순한 DOM 요소가 아니란 점에 주의해야한다.
좀더 설명하자면, directive 를 선언할 때 link 등의 요소에서 element 라는 파라메터를 받게 되는데, 이런 종류의 앵귤러 상의 element 들은 모두 기본적으로 jQuery로 랩핑되어 있다는 것이다. 따라서 두번 랩핑할 필요가 없다. 실제로 콘솔에서 찍어보면 일단 DOM 요소가 아닌 랩핑된 요소임을 쉽게 알 수 있다.
 


jqLite 에서 제공하는 jQuery API

jqLite는 다음과 같은 jQuery 호환 API를 지원해주고 있다.

addClass()
after()
append()
attr()
bind()
children()
clone()
contents()
css()
data()
eq()
find() - 태그 이름에 의한 검색만 가능
hasClass()
html()
next()
parent()
prepend()
prop()
ready()
remove()
removeAttr()
removeClass()
removeData()
replaceWith()
text()
toggleClass()
unbind()
val()
wrap()

위에 더해서 앵귤러에서는 추가적인 아래의 메서드를 지원한다.

controller(name)
injector() 
scope()
inheritedData()




사용 예제


마치며

angular.element API 의 기본적인 사용법은 jQuery와 매우 유사하다. $ 대신에 angular.element 가 들어간다고 생각해도 무방하다. 하지만 셀렉터가 빠져있다는 점이 다르고 AngularJS와 jQuery를 함께 쓰고 싶다면 jQuery를 AngularJS보다 먼저 로드해야한다는 점만 기억하면 큰 문제는 없을 것이다.
 


AngularJS 관련 포스팅 더보기