Service and factory are two important concepts of Angular.
Both are very similar in terms of functionality but they are different.
Service : Service
is singleton in fashion. That mean instance of service will create once for one
application and all user will use same object. Here is syntax of service in
Angular.
module.service( 'serviceName', function );
The first argument is service name and the second argument is one callback function, the function will contain service body. Here is sample code to implement service.
var myapp = angular.module('myapp', []);
//Implement service
myapp.service('myService',
function () {
this.returnData = function () {
return "From Service";
}
})
Factory : Factory is
a function in Angular which allows user to add logic in a object before it created.
Here is syntax for factory.
module.factory( 'factoryName', function );
Here is sample code
to implement factory.
var myapp = angular.module('myapp', []);
//Implement
factory
myapp.factory('myFactory',
function () {
var facObject = new Object();
facObject.returnData = function () {
return "From Factory";
};
return facObject;
})
Ok, so we have learn syntax of both service and factory. Now
let’s implement both in single example. Have a look on below code.
<script>
var myapp = angular.module('myapp', []);
//Implement
factory
myapp.factory('myFactory',
function () {
var facObject = new Object();
facObject.returnData = function () {
return "From Factory";
};
return facObject;
})
//Implement
service
myapp.service('myService',
function () {
this.returnData = function () {
return "From Service";
}
})
//Inject
both service and Factory into controller
myapp.controller('myController',
function ($scope, myFactory,
myService) {
$scope.fromService =
myService.returnData();
$scope.fromFactory =
myFactory.returnData();
});
</script>
And here is the view.
<div ng-app="myapp">
<div ng-controller="myController">
{{fromService}} <br />
{{fromFactory}}
</div>
</div>
Once we run the application, we will see below output.
No comments:
Post a Comment