Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 726
Adelin Avatar asked Nov 07 '12 08:11

Adelin


People also ask

What is $document in AngularJS?

The $document is a jQuery collection, not a direct reference to the HTML document object. When use $document into AngularJS application, it returns a jQuery collection (or jQLite collection) that contains the document object and its properties.

What method is used to implement a service in AngularJS?

Services are normally injected using the dependency injection mechanism of AngularJS.


1 Answers

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.

like image 109
Mark Rajcok Avatar answered Oct 28 '22 11:10

Mark Rajcok