AngularJS:控制器与服务 [英] AngularJS: controller vs service

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

问题描述

我已经阅读了几篇关于正确使用 angularjs 实体的帖子:服务、工厂、控制器和指令.

I have read a couple of posts regarding proper usage of angularjs entities: services, factories, controllers and directives.

我特别关心的是控制器和服务的比较.没有任何帖子告诉我控制器可以做什么服务不能做什么,反之亦然.

My particular concern is a comparison of a controller and a service. None of the posts though told me what is that a controller can do what service cannot and vice versa.

这可以列出还是只是在 angular 的用法中规范化?

Can this be listed or is it just a matter of being canonical in angular's usage?

推荐答案

Controllers 通常用于与视图绑定.控制器管理视图的生命周期,应该被认为是视图控制器.将为视图的每个实例创建一个新控制器,这意味着如果您离开某个视图,然后又返回 - 或者如果您有多个某个视图的实例,则每次都会创建一个新控制器.

Controllers are typically used to be bound with a view. Controllers manage a view's life cycle, and should be thought of as View Controllers. A new controller will be created for each instance of a view, meaning that if you navigate away from a certain view, and then back again - or if you have more than once instance of a certain view, a new controller will be created each time.

服务通常用作应用程序的业务逻辑.服务类似于单例,因为它们只创建一次,并且实例在应用程序的整个生命周期中都得到维护.这是一个放置许多视图或组件需要的逻辑函数的好地方,还保存需要在应用程序中的多个区域访问的全局缓存.

Services are typically used as the business logic of your application. Services are similar to singletons in the sense that they are created once, and the instance is maintained throughout the entire life cycle of your application. It is a good place to put your logical functions which many views or components will require, and also hold global cache which needs to be accessed throughout multiple areas in your application.

这篇关于AngularJS:控制器与服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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