Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Prasanna-Poonacha/7a5b3f633187a48d0be4 to your computer and use it in GitHub Desktop.
Save Prasanna-Poonacha/7a5b3f633187a48d0be4 to your computer and use it in GitHub Desktop.
Service and Factory in Angular
<html ng-app="app">
<body ng-controller="myController">
<p>{{fromService}}</p>
<p>{{fromFactory}}</p>
<p>{{fromFactory2}}</p>
</body>
</html>
var app = angular.module('app',[]).
service('service1',function(){
this.fromService=function(){
return "Service";
}
}).
factory('service2',function(){
return{
fromFactory:function(){
return "Factory";
}
}
}).
factory('service3',function(){
return function(name){
this.name=name;
this.fromFactory2=function(){
return "Hello "+this.name;
}
}
}).
controller('myController',function($scope,service1,service2,service3){
$scope.fromService=service1.fromService();
$scope.fromFactory=service2.fromFactory();
$scope.fromFactory2=new service3('Prasanna').fromFactory2();
})

Service and Factory in Angular

Factories offer slightly more flexibility than services because they can return functions which can then be new'd. This follows the factory pattern from object oriented programming. A factory can be an object for creating other objects.

A Pen by Prasanna Poonacha on CodePen.

License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment