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.
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.
Services are normally injected using the dependency injection mechanism of AngularJS.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With