最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use $document service in angularJS? - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Nov 7, 2014 at 1:24 Ryan 18.1k24 gold badges64 silver badges90 bronze badges asked Nov 7, 2012 at 8:12 AdelinAdelin 19k27 gold badges127 silver badges195 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 10

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.

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

发布评论

评论列表(0)

  1. 暂无评论