AngularJS service vs factory – with example
Also read my answer on stackoverflow (angular.service vs angular.factory).
Yes! That one word is enough to define AngularJS services. The purpose of AngularJS service / factory function is to generate a single object or function that represents the service to rest of the application. That object or function is passed as a parameter to any other factory function which specifies a dependency on this service.
Result: When declaring serviceName as an injectable argument you will be provided with the instance of a function passed to
Usage: Could be useful for sharing utility functions that are useful to invoke by simply appending () to the injected function reference. Could also be run with
Example:
Result: When declaring factoryName as an injectable argument you will be provided the value that is returned by invoking the function reference passed to
Usage: Could be useful for returning a ‘class’ function that can then be new’ed to create instances.
Here is a running code on jsfiddle which you can test and play with.
What is an AngularJS service or factory?
Singleton.Yes! That one word is enough to define AngularJS services. The purpose of AngularJS service / factory function is to generate a single object or function that represents the service to rest of the application. That object or function is passed as a parameter to any other factory function which specifies a dependency on this service.
Services
Syntax:module.service('serviceName', function);
Result: When declaring serviceName as an injectable argument you will be provided with the instance of a function passed to
module.service
.Usage: Could be useful for sharing utility functions that are useful to invoke by simply appending () to the injected function reference. Could also be run with
injectedArg.call(this)
or similar.Example:
var app = angular.module('myApp', []); // Service definition app.service('testService', function(){ this.sayHello= function(text){ return "Service says \"Hello " + text + "\""; }; }); // AngularJS Controller that uses the service function HelloCtrl($scope, testService) { $scope.fromService = testService.sayHello("World"); }
Factories
Syntax:module.factory('factoryName', function);
Result: When declaring factoryName as an injectable argument you will be provided the value that is returned by invoking the function reference passed to
module.factory
.Usage: Could be useful for returning a ‘class’ function that can then be new’ed to create instances.
var app = angular.module('myApp', []); // Factory app.factory('testFactory', function(){ return { sayHello: function(text){ return "Factory says \"Hello " + text + "\""; } } }); // AngularJS Controller that uses the factory function HelloCtrl($scope, testFactory) { $scope.fromFactory = testFactory.sayHello("World"); }
Here is a running code on jsfiddle which you can test and play with.
No comments:
Post a Comment