AngularJS 服务中的 DOM 操作 [英] DOM manipulation in AngularJS services

查看:22
本文介绍了AngularJS 服务中的 DOM 操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,使用 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..

弹出窗口可能是我们可以使用服务的另一种情况,但与对话框不同的是,弹出窗口是附加到 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆