为什么在控制器中操纵DOM是一个坏主意? [英] Why is it considered a bad idea to manipulate DOM in controllers?

查看:106
本文介绍了为什么在控制器中操纵DOM是一个坏主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多人告诉我,在控制器中操纵DOM是一件非常糟糕的事情,但究竟是什么原因。它如何影响您正在制作的应用程序?
最好的做法是什么,怎么做?

解决方案


技术控制器应小于紧凑,不应该是
玩DOM。控制器只有兴趣有一个业务逻辑和


根据我的观点,之后的原因你不应该操纵DOM控制器是,这只是因为担心的分离。如果您从控制器执行DOM操作,那么它会紧密耦合到您的控制器&那段代码不能重复使用。因此,通过在指令中编写该代码,相同的代码可以很容易地成为可插拔&可重复使用的组件。您可以通过放置指令标签/元素来使用相同的DOM操作。



查看指令定义,然后您将分析它只是想与DOM一起玩,因为在使用 preLInk 函数&还可以发布DOM,您可以在 postLink 函数中获取DOM。



此外,指令使您可以使用指令元素,您不需要编译,因为元素已经使用 jQLite 编译,这是使用角度较小的jQuery版本。不需要选择器来获取指令元素DOM。


Many People have told me that it is a very bad thing to manipulate DOM in controllers, but what exactly is the reason. How does it affect the application that you are making? What are the Best Practices to do that and how is it done?

解决方案

Technically controller should be smaller & compact, it should not be playing with a DOM. Controller will only interested to have a business logic & binding level logic that are being called on events.

As per my perspective the reason behind "You should not manipulate DOM from the controller" is, It's just because of separation of concern. If you do the DOM manipulation from the controller then it gets tightly coupled to your controller, & that piece of code can't become reusable. So by writing that code in directive, the same code could be easily become a plug-able & reusable component. You can use the same DOM manipulation elsewhere just by putting directive tag/element.

Looked at directive definition, then you will analysed that it just meant to play with DOM, as it give a controller over DOM before rendering it using preLInk function & also post rendering of DOM you can get in postLink function.

Also directive make you available the directive element, you no need to make it compile because that element has already compiled with jQLite which is smaller version of jQuery used in angular. No need of selector here to get directive element DOM.

这篇关于为什么在控制器中操纵DOM是一个坏主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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