Johann
Johann

Reputation: 29885

How should one organize AngularJS services

The following is written about AngularJS services:

Angular services are substitutable objects that are wired together using dependency injection (DI). You can use services to organize and share code across your app.

AngularJS Services

Does "substitute objects...shared across your app" mean that you should store these services in separate javascript files and if so, how do you include these files into an AngularJS app?

Upvotes: 0

Views: 128

Answers (1)

Michael Kang
Michael Kang

Reputation: 52867

You can store them in separate files, but best practice is to group reusable functionality in a module as one file:

my-module.js:

Group related services, directives, factories, filters, controllers, etc into a re-usable module.

 var module = angular.module('myModule',[ /* dependent modules go here */ ]);
 module.service('service1', ...);
 module.service('service2', ...);
 module.factory('factory1,'...); 
 module.controller('myController', ...);
 etc

JS:

Once you have everything contained in a module, add your module as a dependency for any app:

var app = angular.module('app', ['myModule']);
...

HTML:

Make sure that you include the script file in your HTML.

<head>
     <script type="text/javascript" src="angular.js" />
     <script type="text/javascript" src="myModule.js" />
</head>
<body ng-app="app">

     <div ng-controller="myController"> // controller defined in myModule.js
         ... 
     </div>
</body>

To help ensure that there is no naming conflicts between directives, give your module a unique prefix and use that prefix in your directives. In the above example, the prefix is 'my'.

Upvotes: 2

Related Questions