Hello All
In today's blog post we would discuss the aspect of registering your custom services with AngularJS.
It is essential to understand what are AngularJS services.
Services:
Angular services are objects that are packed together using dependency injection. You can use services to organize and share code across your app.
Use of Angular Service:
- to have the data available through out the lifetime of the app.
- to provide data to controllers consistently
- to enable data and function sharing throughout the application.
Features of service:
A service can be created using the following methods:
- service()
- factory()
- provider()
- value()
- constant()
In this post we would discuss about using the service() method.
To declare the service
var module = angular.module('myapp', []);
module.service('demoService', function(){
this.users = [user1, user2, user3];
});
A constant value as service can be registered in any of the Module type:
- constant(name, value). It is used only for constants and to register configuration data.
- value(name, value): It is used to register an existing instance of an object or function.
In .service the methods of the service are created using this.methodname.
Sample App:
HTML:
<div ng-app="app">
<div ng-controller="CalculatorController">
Enter a number:
<input type="number" ng-model="number" />
<button ng-click="doSquare()">X<sup>2</sup></button>
<button ng-click="doCube()">X<sup>3</sup></button>
<div>Answer: {{answer}}</div>
</div>
</div>
Javascript
var app = angular.module('app', []);
app.service('MathService', function() {
this.add = function(a, b) { return a + b };
this.subtract = function(a, b) { return a - b };
this.multiply = function(a, b) { return a * b };
this.divide = function(a, b) { return a / b };
});
app.service('CalculatorService', function(MathService){
this.square = function(a) { return MathService.multiply(a,a); };
this.cube = function(a) { return MathService.multiply(a, MathService.multiply(a,a)); };
});
app.controller('CalculatorController', function($scope, CalculatorService) {
$scope.doSquare = function() {
$scope.answer = CalculatorService.square($scope.number);
}
$scope.doCube = function() {
$scope.answer = CalculatorService.cube($scope.number);
}
});;
0 Comment(s)