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() { ... });
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.
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.
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);
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With