Factory is used for large code but to expose some of the variables and functions that are useful. factory return an object.
Syntax:
myModule.factory("factoryName", function(){
//code goes here
return {
// functions/varibles to expose
}
});
Example:
angular.module('myApp.factory',[]).factory('myfactory', function(){
function calculteArea(s) {
var area = s * s;
alert(area);
}
return {
areaOfScure: calculteArea;
}
});
Inject factorynamr in controller to use it's methods.
angular.module('myApp.controller',[]).controller('demoController1',['$scope','myfactory',function($scope, helloService){
myfactory.areaOfScure(10);
}]);
output:
return an alert with 100 as area.
Syntax:
myModule.factory("factoryName", function(){
//code goes here
return {
// functions/varibles to expose
}
});
Example:
angular.module('myApp.factory',[]).factory('myfactory', function(){
function calculteArea(s) {
var area = s * s;
alert(area);
}
return {
areaOfScure: calculteArea;
}
});
Inject factorynamr in controller to use it's methods.
angular.module('myApp.controller',[]).controller('demoController1',['$scope','myfactory',function($scope, helloService){
myfactory.areaOfScure(10);
}]);
output:
return an alert with 100 as area.