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. commonModule.factory('heroCommonHelper', ["$filter", "$injector",
  4. function ($filter, $injector) {
  5. var self = this;
  6. //Money Format
  7. self.moneyFormat =
  8. function (money) {
  9. return $filter('currency')(money, "$", 2);
  10. };
  11. //Date Format
  12. self.dateDisplay =
  13. function (date) {
  14. return $filter('date')(date, heroConstants.defaultDateFormat);
  15. };
  16. //Date Time Format
  17. self.dateTimeDisplay =
  18. function (dateTime) {
  19. return $filter('date')(dateTime, heroConstants.defaultDateTimeFormat);
  20. };
  21. }]);
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. myApp.controller('myAppController', ["$compile", "$scope", "$window", "myCommonHelper", "$filter",
  4. function ($compile, $scope, $window, myCommonHelper, $filter) {
  5. $scope.init = function () {
  6. var formatedDate = myCommonHelper.dateDisplay("PASS DATE HERE");
  7. };
  8. }]);