0

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?

1
  • 1
    You would include them the same as any other JS file, but that's not what they meant... They meant to use them as a separate, stand-alone pieces of code that usually have one specific purpose (being in a separate file or not) and as such inject them into controllers or other services as needed. Commented Jun 12, 2014 at 11:27

1 Answer 1

2

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'.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.