Adelin
Adelin

Reputation: 18991

How to use $document service in angularJS?

I am very new to angularJS in JS in general and I am a bit confused about using $document. According to what I understood $document exposes some JQuery functions. So, when I want to remove an element matching a selector I do this :

$document.remove('.someClassSelector');  

and the element should be removed from the DOM tree, right ? If not what is the correct way to manipulate DOM elements and their css in angular.

Upvotes: 7

Views: 19782

Answers (2)

Florian F
Florian F

Reputation: 8875

AngularJS embed a lite version of Jquery (jqLite).

If you want to use jqLite only (without embedding jquery), you can do the following to remove the element :

angular.element(yourElement).remove()

$document is a jqLite shortcut to window.document

See : docs.angularjs.org/api/angular.element

Upvotes: 5

Mark Rajcok
Mark Rajcok

Reputation: 364707

The more common "angular way" of hiding/showing DOM elements is to use the ngHide and/or ngShow directives -- "declare" them in your HTML (hence this statement on the Overview page:

Angular is built around the belief that declarative code is better than imperative when it comes to building UIs and wiring software components together

Similarly, to add/remove CSS classes, use the ngClass directive in a declarative manner. Changes to your models (i.e., $scope properties) should drive the hiding/showing and the addition/removal of CSS classes.

If you need something more complicated, put DOM manipulation into custom directives, normally in the link function.

In a jQuery world, we think about events triggering DOM manipulation code (e.g., call remove() on some element). In an AngularJS world, we want to think about events triggering model changes, which then trigger UI changes automatically, based on our declarative HTML (e.g., an ng-click sets a $scope property which is tied to an ng-show on an element). I'm still adjusting my thinking.

For most AngularJS applications, you won't need to use $document.

Upvotes: 10

Related Questions