如果我多个controller共享一份数据,是在某个比较上层的控制器上保存数据,还是用factory保存这个需要共享的数据,如果用service会怎么样。
为情所困2017-05-15 16:55:11
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.
滿天的星座2017-05-15 16:55:11
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
滿天的星座2017-05-15 16:55:11
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.