Angular Service Example

The following code demonstrates how a service can be created in AngularJS.

index.html

<html>
 <head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-route.min.js"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-animate.min.js"></script>
 <script src="app.js"></script>
 <script src="anotherModule.js"></script>
 </head>
 <body>
 <div ng-app="mainModule" ng-controller="mainController as alias">
 <b>Invoice:</b>
 <p>The input is: {{alias.quantity}}</p>
 <div>
 Quantity: <input type="number" min="0" ng-model="alias.quantity"required>
 </div>
 <div><p>Add 4 and double it!</p></div>
 <div>
 <b>Result:</b>
 <span>{{alias.total(alias.quantity)}}</span>
 <button class="btn" ng-click="alias.paid(alias.total(alias.quantity))">Pay</button>
 </div>
 </div>
 </body>
</html>

app.js

angular.module('mainModule', ['dependencyModule'])
.controller('mainController', ['theService', function(theService) {

  this.quantity = 1;

  this.total = function total(number) {
    return theService.inService(number + 4);
  };

  this.paid = function pay(parameter) {
    window.alert(parameter);
  };

}]);

anotherModule.js

angular.module('dependencyModule', [])
  //currencyConverter is the service
.factory('theService', function() {

  var functionInService = function (parameter2) {
    return parameter2 * 2;
  };

  return {
    inService: functionInService
  };
});

Services can be used to share code across controllers.