Angular JS Angular services
Dependency injection AngularJS comes with a built-in dependency injection mechanism. You can divide your application into multiple different types of components which AngularJS can inject into each other. Modularizing your application makes it easier to reuse, configure and test the components in your application. AngularJS contains the following core types of objects and components: Value Factory Service Provider Constant
Angular layered application architecture
Value var myModule = angular.module("myModule", []); myModule.value("numberValue", 999); myModule.controller("MyController", function($scope, numberValue) { console.log(numberValue); }); A value is a simple object which can be passed to the controllers or services.
Factory Factory is a function that creates values. var myModule = angular.module("myModule", []); myModule.factory("myFactory", function() { return "a value"; }); myModule.controller("MyController", function($scope, myFactory) { console.log(myFactory); });
Service A service in AngularJS is a singleton JavaScript object which contains a set of functions. function MyService() { this.value = 5; this.doIt = function() { console.log("done “+this.value); } var myModule = angular.module("myModule", []); myModule.service("myService", MyService); myModule.controller("MyController", function($scope, myService) { myService.doIt(); // will print “done 5" }); AngularJS do it internally: var theService = new MyService();
Service vs. Factory
Injecting Values Into a Service myModule.value("myValue", "12345"); function MyService(myValue) { this.doIt = function() { console.log("done: " + myValue); } myModule.service("myService", MyService); Notice how the parameter to the MyService function is named the same as the value registered on the module. Thus, the value will be injected into the service when it is created.
Providers Providers is the most flexible form of factory you can create. myModule.provider("mySecondService", function() { var provider = {}; provider.$get = function() { var service = {}; service.doIt = function() { console.log(“Service Done!"); } return service; } return provider; }); myModule.controller("MyController", function($scope, mySecondService) { $scope.whenButtonClicked = function() { mySecondService.doIt(); } }); $get() function creates whatever the provider creates (service, value etc.)
Configuring a provider myModule.provider("mySecondService", function() { var provider = {}; var config = { configParam : "default" }; provider.doConfig = function(configParam) { config.configParam = configParam; } provider.$get = function() { /* use config.configParam */} return provider; }); myModule.config( function(mySecondService) { // WON'T WORK -- mySecondService is an instance of a service – not provider mySecondService.doConfig("new config param"); });
Configuring a provider myModule.provider("mySecondService", function() { var provider = {}; var config = { configParam : "default" }; provider.doConfig = function(configParam) { config.configParam = configParam; } provider.$get = function() { /* use config.configParam */} return provider; }); myModule.config( function( mySecondServiceProvider ) { mySecondServiceProvider.doConfig("new config param"); }); myModule.controller("MyController", function($scope, mySecondService) { $scope.whenButtonClicked = function() { mySecondService.doIt(); } });
Constants myModule.constant("configValue", "constant config value"); myservices.config( function( mySecondServiceProvider, configValue ) { mySecondServiceProvider.doConfig(configValue); }); Constants in AngularJS are defined using the module.constants() function:
Dependencies Between Modules var myUtilModule = angular.module("myUtilModule", []); myUtilModule.value ("myValue", "12345"); var myOtherModule = angular.module("myOtherModule", ['myUtilModule']); myOtherModule.controller("MyController", function($scope, myValue) { });
Multi-module architecture
Using decorator: service example angular.module('thirdParty', []).service(' Service', function() { this. = ""; this.setContent = function(content) { this. = content; }; this.send = function(recipient) { return 'sending "' + this. + '" to ' + recipient; }; });
Using decorator to extend service var app = angular.module('myApp', ['thirdParty']); app.decorator(' Service', function($delegate) { $delegate.sendWithSignature = function(recipient, signature) { return 'sending "' + this. + '" to ' + recipient + " by " + signature; }; return $delegate; }); app.controller('MainCtrl', function($scope, Service) { Service.setContent("Greeting!!"); $scope. Complete = Service.sendWithSignature 'tamakisquare'); });
Using decorator to customize directive app.directive("user", function() { return { replace: true, template: ' This is foo directive ' }; }); app.decorator('userDirective', function($delegate) { var directive = $delegate[0]; directive.restrict = "AE"; return $delegate; }); Notice that we have to add postfix "Directive" original directive instance
Minification Safe Dependency Injection in AngularJS var myapp = angular.module("myapp", ['myservices']); myapp.controller("AController", ['$scope', '$http', function(p1, p2) { p1.myvar = "the value"; p2.get("/myservice.json"); }]); When you minify JavaScript the JavaScript minifier replaces the names of local variables and parameters with shorter names.
Internationalization {{theDate | date : "fullDate"}} {{theValue | currency }} var module = angular.module("myapp", []); module.controller("mycontroller", function($scope) { $scope.theDate = new Date(); $scope.theValue = ; }); date filter: short medium fullDate shortDate mediumDate longDate shortTime mediumTime number filter: {{ theValue|number }} currency filter: {{ theValue | currency : '£' }}
Cross-controller communication: events // dispatches the event upwards through the // parent controller scope hierarchy $scope.$emit('myCustomEvent', 'Data to send'); // broadcast dispatches the event downwards to all child scopes $scope.$broadcast('myCustomEvent', { someProp: 'Sending you an Object!' // any object }); // listening in any $scope $scope.$on('myCustomEvent', function (event, data) { console.log(data); });
Cross-controller communication: use services Controller can use service properties and methods for communication.
Summary