Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Service in different file

Tags:

angularjs

I'm learning AngularJS following an organization inspired by ng-boilerplate. I create different Angular modules for the different parts of my site.

However, I want to create all common elements (services and directives) under the main module, while having them all be in separate source files.

This code works, but is the module in sessionService.js referencing the same module than app.js, or is it creating a new one with the same name?

app.js

var app = angular.module('myApp', [...])
.config(...)
.controller(...);

sessionService.js

angular.module('myApp', [])
.service('SessionService', function() { ... });
like image 504
Kore Avatar asked Dec 29 '13 00:12

Kore


People also ask

What are the services in AngularJS?

AngularJS 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 are: Lazily instantiated – AngularJS only instantiates a service when an application component depends on it.

What is service and factory in AngularJS?

factory() is a method that takes a name and function that are injected in the same way as in service. The major difference between an AngularJS service and an AngularJS factory is that a service is a constructor function and a factory is not.

How to return value from function in AngularJS?

function formatGreeting(name, city){ var retStr = ""; retStr += "Hello <b>" + name + "/n"); retStr += "Welcome to " + city + "!";return retStr;}var greeting = formatGreeting("Brad", "Rome");console. log(greeting);


2 Answers

If you call angular.module('myApp', []) multiple times on the same page, you will likely run into errors or conflicts. I never tried that.

However, if you already run angular.module('myApp', []) once. Then you can run angular.module('myApp') (note: without []) to retrieve (refer to) the myApp module you defined earlier.

like image 189
Daiwei Avatar answered Oct 03 '22 06:10

Daiwei


in controller.js file :

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

in service.js :

angular.module('newService',[])

.service('someService',function(){

    return {
         // return something
         return null
         }
    }

});

Do not forget to include both the js files in your HTML:

<script src="controllers/controller.js" type="text/javascript"></script>
<script src="services/service.js" type="text/javascript"></script>
like image 43
Ajay V Avatar answered Oct 03 '22 08:10

Ajay V