How To Create And Use Common Functions In AngularJS

Learn how to create and use common functions in AngularJS.

Often in our applications, we reuse code. In an Angular application, we can create some common methods/functions that can be reused in our entire Angular app.

Here, I'll create a new factory file namely "my-common-helper.js" to write common methods such as display money, date and time in uniform look or show/hide loader, etc.
  1. "use strict";  
  2. var commonModule = angular.module('common', ['ngRoute''ngResource''ngMaterial']);  
  3.   
  4. commonModule.factory('heroCommonHelper', ["$filter""$injector",  
  5.     function ($filter, $injector) {  
  6.         var self = this;  
  7.           
  8.         //Money Format  
  9.         self.moneyFormat =  
  10.             function (money) {  
  11.                 return $filter('currency')(money, "$", 2);  
  12.             };  
  13.           
  14.         //Date Format  
  15.          self.dateDisplay =  
  16.             function (date) {  
  17.                 return $filter('date')(date, heroConstants.defaultDateFormat);  
  18.             };  
  19.           
  20.         //Date Time Format   
  21.         self.dateTimeDisplay =  
  22.             function (dateTime) {  
  23.                 return $filter('date')(dateTime, heroConstants.defaultDateTimeFormat);  
  24.             };                
  25.           
  26.     }]); 
Now we will see how we can use this common factory's method inside our js.
  1. "use strict";  
  2. var myApp = angular.module('myApp', []);  
  3.   
  4. myApp.controller('myAppController', ["$compile""$scope""$window""myCommonHelper""$filter",  
  5.     function ($compile, $scope, $window, myCommonHelper, $filter) {  
  6.       
  7.       $scope.init = function () {  
  8.           
  9.         var formatedDate = myCommonHelper.dateDisplay("PASS DATE HERE");  
  10.         
  11.       };  
  12.       
  13. }]);