Www.luxoft.com Angular JS Angular services. Dependency injection AngularJS comes with a built-in...
-
Upload
clare-nelson -
Category
Documents
-
view
227 -
download
0
Transcript of Www.luxoft.com Angular JS Angular services. Dependency injection AngularJS comes with a built-in...
www.luxoft.com
Angular JS
Angular services
www.luxoft.com
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
www.luxoft.com
Angular layered application architecture
www.luxoft.com
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.
www.luxoft.com
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); });
www.luxoft.com
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();
www.luxoft.com
Service vs. Factory
www.luxoft.com
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.
www.luxoft.com
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.)
www.luxoft.com
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");
});
www.luxoft.com
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(); } });
www.luxoft.com
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:
www.luxoft.com
Dependencies Between Modules
var myUtilModule = angular.module("myUtilModule", []);
myUtilModule.value ("myValue", "12345");
var myOtherModule = angular.module("myOtherModule",
['myUtilModule']);
myOtherModule.controller("MyController", function($scope, myValue) {
});
www.luxoft.com
Multi-module architecture
www.luxoft.com
Using decorator: service example
angular.module('thirdParty', []).service('emailService', function() {
this.email = "";
this.setContent = function(content) { this.email = content; };
this.send = function(recipient) { return 'sending "' + this.email +
'" to ' + recipient; };
});
www.luxoft.com
Using decorator to extend service
var app = angular.module('myApp', ['thirdParty']);
app.decorator('emailService', function($delegate) {
$delegate.sendWithSignature = function(recipient, signature) {
return 'sending "' + this.email + '" to ' +
recipient + " by " + signature; };
return $delegate;});
app.controller('MainCtrl', function($scope, emailService) {
emailService.setContent("Greeting!!");$scope.emailComplete =
emailService.sendWithSignature(‘[email protected]',
'tamakisquare');});
www.luxoft.com
Using decorator to customize directive
app.directive("user", function() { return { replace: true, template: '<div>This is foo directive</div>' };});
app.decorator('userDirective', function($delegate) { var directive = $delegate[0]; directive.restrict = "AE"; return $delegate;});
<body ng-controller="MainCtrl"> <div user></div></body>
<body ng-controller="MainCtrl"> <user></user></body>
Notice that we have to add postfix "Directive"
original directive instance
www.luxoft.com
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.
www.luxoft.com
Internationalization
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script><script src="https://code.angularjs.org/1.2.5/i18n/angular-locale_en-uk.js"></script>
<body ng-app="myapp"><div ng-controller="mycontroller"> {{theDate | date : "fullDate"}} <br/> {{theValue | currency }}</div>
<script> var module = angular.module("myapp", []); module.controller("mycontroller", function($scope) { $scope.theDate = new Date(); $scope.theValue = 123.45; });</script></body>
date filter:shortmediumfullDateshortDatemediumDatelongDateshortTimemediumTime
number filter:{{ theValue|number }}
currency filter:{{ theValue | currency : '£' }}
www.luxoft.com
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);});
www.luxoft.com
Cross-controller communication: use services
Controller can use service properties and methods for communication.
www.luxoft.com
Summary