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.
- "use strict";
- var commonModule = angular.module('common', ['ngRoute', 'ngResource', 'ngMaterial']);
-
- commonModule.factory('heroCommonHelper', ["$filter", "$injector",
- function ($filter, $injector) {
- var self = this;
-
-
- self.moneyFormat =
- function (money) {
- return $filter('currency')(money, "$", 2);
- };
-
-
- self.dateDisplay =
- function (date) {
- return $filter('date')(date, heroConstants.defaultDateFormat);
- };
-
-
- self.dateTimeDisplay =
- function (dateTime) {
- return $filter('date')(dateTime, heroConstants.defaultDateTimeFormat);
- };
-
- }]);
Now we will see how we can use this common factory's method inside our js.
- "use strict";
- var myApp = angular.module('myApp', []);
-
- myApp.controller('myAppController', ["$compile", "$scope", "$window", "myCommonHelper", "$filter",
- function ($compile, $scope, $window, myCommonHelper, $filter) {
-
- $scope.init = function () {
-
- var formatedDate = myCommonHelper.dateDisplay("PASS DATE HERE");
-
- };
-
- }]);