AngularJS服务中的DOM操作 [英] DOM manipulation in AngularJS services
问题描述
众所周知,在使用AngularJS时,必须使用指令中的DOM元素。
It's well known that you must manipulate DOM elements inside directives when using AngularJS.
然而,在某些用例中,操作DOM内部的服务似乎是可以接受的。
Misko Hevery正在谈论此此处 。您还可以在 Bootstrap UI对话框一>。
However, it seems that, in some use cases, manipulating DOM inside a service is acceptable. Misko Hevery is talking about this here. You can also find an example within the Bootstrap UI Dialog.
Misko的解释很模糊,所以我想知道如何确定何时需要将DOM放在服务中而不是指令。
Misko's explanation is rather vague so I was wondering how do you determine when you need to put DOM inside a service instead of a directive.
推荐答案
一个指令,以定义的方式,始终附加到DOM节点。所以当你定义一个指令时,它会展开或者替换它附加到的DOM节点。
A directive, with the way it is defined, is always attached to a DOM node. So when you define a directive, it "expands" or replaces the DOM node to which it is attached.
在某些情况下(如对话框),您将无法将DOM节点附加到任何特定的父项。在这些情况下,使用服务是有意义的,并且控制器仍然可以脱离DOM位,因为DOM操作将被封装在服务中。
In certain situations (like dialogs) you won't be able to attach DOM nodes to any specific parent. In these cases using a service makes sense and the controller can still stay out of the DOM bit because the DOM manipulation will be encapsulated in a service..
弹出窗口可能是另一个我们可能会使用服务的情况,但与对话框不同,弹出的IS附加到DOM节点。所以,即使这是一个灰色的地方。
Popups could be another situation where we could probably use a service, but unlike a dialog, a popup IS attached to a DOM node. So, even that is slightly a grey area.
所以,一个基本和简单的测试是,DOM操作代码的这一点可以附加到DOM节点吗?如果是,那么指令。如果没有,那么服务。
So, a basic and simple test is, "Can this bit of DOM Manipulation code be attached to a DOM node?" If yes, then directive. If no, then service.
对话框和自定义确认框作为您使用服务的典型示例。
Dialogs and Custom Confirm Boxes come in as typical examples where you would use a service.
这篇关于AngularJS服务中的DOM操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!