What are Services in AngularJs
According to AngularJs Documentation Services are substitutable objects that are wired together using dependency injection (DI). You can use services to organize and share code across your app.
It lists two important properties of AngularJs services
It lists two important properties of AngularJs services
- Lazily instantiated – Angular only instantiates a service when an application component depends on it.
- Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.
There are some useful built in services such as
$http
and $animate
offered by angular but services can be implemented according to needs in application.Creating a service
To define your own service in Angular first we need to register the service name and service factory function with an angular module.
Registering a service
In here we will register a factory function that will create a instance when it is called.
This is a template provided by angular to register a service
This is a template provided by angular to register a service
var myModule = angular.module('myModule', []);
myModule.factory('serviceId', function() {
var shinyNewServiceInstance;
// factory function body that constructs shinyNewServiceInstance
return shinyNewServiceInstance;
});
Now lets refer an example of using service.It is a simple calculator that add user inputs
Demo
Find Sum
Enter a number:
Result: 0
Result: 0
Steps
- Registering a service
var app=angular.module("App",[]); app.factory("createSum",function(){ var obj={}; obj.sum=0; obj.add=function (val){ this.sum+=val; return this.sum; }; obj.clear=function(){ this.sum=0; return this.sum; } return obj; });
- Use that service with a controller
app.controller("myController",['$scope',"createSum",function($scope,createSum){ $scope.result=createSum.sum; $scope.showSum=function(num){ $scope.result=createSum.add(num); } $scope.clearSum=function(){ $scope.result=createSum.clear(); } }]);
- Binding data with models
<h2>Find Number of factors</h2> <div ng-app = "App" ng-controller="myController"> <p>Enter a number: <input type = "number" ng-init="number=0"ng-model = "number" /> <button ng-click = "showSum(number)"> + </button> <button ng-click="clearSum()">Clear</button> </p> <p>Result: {{result}}</p> </div>
No comments:
Post a Comment