服务、指令和模块之间有什么区别? [英] What is the difference between service, directive and module?

查看:36
本文介绍了服务、指令和模块之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了很多文档,但我越来越困惑.我基本上无法弄清楚

I have been reading a lot of docs, and I'm getting more and more confused. I basically can't figure out the difference between a

  • 服务
  • 指令
  • 模块

我看到很多自定义组件.有时他们使用指令,有时使用服务.它总是从一个模块开始.有人能举例说明这三种类型有什么区别吗?

I see a lot of custom components. Sometimes they're using directives, sometimes services. It always starts with a module. Can someone explain with an example what the difference is between these three types?

推荐答案

将模块视为连接许多其他事物(例如指令、服务、常量等)的地方.模块可以注入其他模块为您提供高水平的重用.

Think of a module as being a place to wire up a number of other things, such as directives, services, constants etc. Modules can be injected into other modules giving you a high level of reuse.

在编写 Angular 应用程序时,您将拥有一个顶级模块,它是您的应用程序代码(没有模板).

When writing an angular app, you would have a top-level module which is your application code (without templates).

服务主要是控制器之间通信的一种方式,但您可以将一个服务注入到另一个服务中.服务通常用作获取数据存储的一种方式,人们会包装 angular API,例如 ngResource.这种技术很有用,因为它使测试(尤其是模拟)变得非常容易.您可以拥有用于执行其他操作的服务,例如身份验证、日志记录等.

Services are mainly a way to communicate between controllers, but you can inject one service into another. Services are often used as a way to get to your data stores and people will wrap the angular APIs, such as ngResource. This technique is useful since it makes testing (particularly mocking) quite easy. You can have services for doing other things like authentication, logging etc.

指令用于创建小部件或包装现有的东西,如 jquery 插件.包装现有插件可能是一个挑战,你这样做的原因是在插件和 angular 之间建立双向数据绑定.如果你不需要双向数据绑定,那么你就不需要包装它们.

Directives are used for creating widgets or wrapping existing things like jquery plugins. Wrapping existing plugins can be a challenge and the reason you would do this is to establish a two-way data binding between the plugins and angular. If you don't need two-way data binding then you don't need to wrap them.

指令也是进行 DOM 操作、捕捉 DOM 事件等的地方.你不应该在控制器或服务中做与 DOM 相关的事情.创建指令可能会变得非常复杂.恕我直言,我建议您首先查看 API 以获得可以满足您需求的功能,或者向 Angular 的 Google Group 寻求建议.

A directive is also a place for doing DOM manipulation, catching DOM-events etc. You should not be doing DOM-related stuff in controllers or services. Creating directives can get pretty complex. IMHO, I recommend first looking at API for something that can do what you are looking for OR ask Angular's Google Group for advice.

这篇关于服务、指令和模块之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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