Search code examples
angularjsangularjs-factory

Correct way to make a factory module in angularJs


I have a controller function like this:

$scope.localTimezone = function (userTimezone,datetime) {
  // ....
  return data;
}

What is the correct way to make it a factory module? I tried the following but it's giving errors.

angular.module('localTimezone',  [])
   .factory('localTimezone',function(userTimezone,datetime) {
      // ...
      return data;
   });


angular.module('app', ['localTimezone'])
   .controller('tasksController',function ($scope,localTimezone) {
     // ...
   });

I am missing out on some concept or logic.Can anyone please point me in the right direction?


Solution

  • CONTROLLER Example Bad:

    function MainCtrl () {
      this.doSomething = function () {
    
      };
    }
    angular
      .module('app')
      .controller('MainCtrl', MainCtrl);
    

    Good:

    function MainCtrl (SomeService) {
      this.doSomething = SomeService.doSomething;
    }
    angular
      .module('app')
      .controller('MainCtrl', MainCtrl);
    

    Factory Example Bad:

    function AnotherService () {
    
      var someValue = '';
    
      var someMethod = function () {
    
      };
    
      return {
        someValue: someValue,
        someMethod: someMethod
      };
    
    }
    angular
      .module('app')
      .factory('AnotherService', AnotherService);
    

    Good:

    function AnotherService () {
    
      var AnotherService = {};
    
      AnotherService.someValue = '';
    
      AnotherService.someMethod = function () {
    
      };
    
      return AnotherService;
    }
    angular
      .module('app')
      .factory('AnotherService', AnotherService);
    

    For Detail Guidelines go through this blog : Opinionated AngularJS styleguide for teams