Example of Creating Basic Factory and Service in AngularJS

mainApp2.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
};
return factory;
});

mainApp2.service('CalcService', function(MathServic){
this.square = function(a) {
return MathService.multiply(a,a);
};
});

mainApp2.controller('CalcController', function($scope, CalcService) {
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
};
});

<div ng-app="mainApp2" ng-controller="CalcController">
<p>Enter a number: <input type="number" ng-model="number" />
<button ng-click="square()">X<sup>2</sup></button>
<p>Result: {{result}}</p>
<a ng-click="alert()">Click</a
</div>

Code snippets from TutorialsPoint

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInPrint this pageEmail this to someone

Leave a Reply

Your email address will not be published. Required fields are marked *