AngularJS: controller vs service

后端 未结 4 2184
-上瘾入骨i
-上瘾入骨i 2020-12-13 02:16

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

相关标签:
4条回答
  • 2020-12-13 02:47

    In addition to what have been said above. Controllers may also hold the logic of your application while the application isn't so big. But as you application grows you would need to move the logic to use services(like factory). This would allow variables and functions needed around your application to be easily accessible.

    0 讨论(0)
  • 2020-12-13 02:48

    controllers - responsibilities: initialize the view, mediate interaction between view/scope and services. It has dependencies on the view and model, but is more concerned with the view and making it work.

    services - responsibilities: provides business services that is not dependent on the view or the controller. Its primary concern is delivering services, regardless of the consumer (controller/view/other services).

    I'm not convinced if persistence factors into the differences.

    0 讨论(0)
  • 2020-12-13 03:01

    As per the AngularJS documentation, https://docs.angularjs.org/guide/concepts

    Controllers are to do with view related business logic. Services, on the other hand, are to do with reusable business logic independent of the views.

    0 讨论(0)
  • 2020-12-13 03:03

    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.

    0 讨论(0)
提交回复
热议问题