angular.js - Problems with Angular's controller, service, and factory
怪我咯
怪我咯 2017-05-15 16:53:11
0
3
574

If I share a piece of data with multiple controllers, should I save the data on an upper-level controller or use a factory to save the data that needs to be shared? What will happen if I use a service.

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(3)
为情所困

This question depends on how strong the business relevance of the data is in your scope level when you use the data.

Strong, that is to say, you are very sure that when a certain scope uses it, you can definitely find a certain parent scope by searching upward, then you can use the inheritance of the scope to share it. However, it is recommended to use controller as 的语法给每一个 controller 唯一的命名空间以避免对象重名。实际上你甚至可以把这个数据保存在 $rootScope 来全局共享(但是不推荐,因为 $rootScope (the lighter the better), or you can have a top-level global controller to save it.

Not strong, that is to say, you cannot determine when and where this data will be used, so use dependency injection. For pure data, it is recommended to use module.value (可变数据)或 module.constant(不可变数据),当然也可以用 module.factory 返回一个对象(这就和 module.value 一样一样的)。module.service which is often used to return a constructor. You can use it to generate different object instances (different from other singleton services).

In fact, module.value/constant/factory/service 全都是 module.provider is a variant (syntactic sugar). Read the chapter about dependency injection and services in the official documentation and you will understand it all.

滿天的星座

Use service. Service is generally used to store data, and factory is generally used to call multiple services~ or return methods. Of course, the functions can be interoperated. In fact, they feel similar. As for their differences, you can check this Or this

滿天的星座

Actually, I don’t find any difference between factory and service. If you like js object, then choose the former. If you like js oop, then use service. . . One translation explains it this way.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template