Is it possible to create an AngularJS service without a module?

て烟熏妆下的殇ゞ 提交于 2019-12-11 04:55:51

问题


In AngularJS there is a short form to create controllers, so you do not have to use a module for this. This short form is to simply define a function

function FooController ($scope) {
  // ...
}

and reference it from the HTML markup using ng-controller:

<div ng-controller="FooController">
  ...
</div>

Now, my question is, whether there is a similar "short form" to define services? In other words: Can you define (and use) a service without using a module?

Please note that I know that it perfectly makes sense to structure your applications using modules, and not doing so could / should be regarded as bad practice. It's just that I am explaining AngularJS to someone who's completely new to it, and the question arose today. So it's just for curiosity and completeness.


回答1:


Quoted from the doc of Creating Services

To register a service, you must have a module that this service will be part of.

So I guess the answer is no.




回答2:


Since the ng module is always loaded, you could define your service on the ng module:

angular.module('ng')
  .service('aService', function () {
    // you really shouldn't do this
  });

It works, but you shouldn't be messing with a module that you don't own.

If you're trying to explain to someone why using your own modules with .controller is good:

  • Talk to them about testing. It's a lot easier to mock things if you're using modules
  • If you need to have other modules as dependencies (like angular-ui)
  • If you want to decorate another service (e.g. $http)
  • If you need to register directives, filters, animations, etc.
  • It's a lot nicer to have modular code :)



回答3:


It's an angular concept I don't understand at all, I always believed "separation" is good, so I dont get why we need to associate a service to a specified application.

Here what I am doing: you can declare your angularjs application as a global object:

window.markrApplication = angular.module('markrOptionsApp', ....)

And declare all your services like this:

markrApplication.service('data', ....

Of course you need to have all the dependencies set on all your angularjs application.



来源:https://stackoverflow.com/questions/18317357/is-it-possible-to-create-an-angularjs-service-without-a-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!