javascriptangularjsfactoryangularjs-factory

Angular factory and its functions calling each other


How can I refer to a function inside a factory? Here is the example, I want function2 to use function1 while returning a result (which fails as it is):

angular.module('myapp').
  factory('ExampleFactory', function ($http, $rootScope) {
  return {
    function1: function (a,b) {
      return a + b;
    },
    function2: function (a,b,c) {
      return this.function1(a,b) * c
    },    
  }
})

Solution

  • Here is one option using the "Revealing Module" design pattern:

    angular.module('myapp').
      factory('ExampleFactory', function ($http, $rootScope) {
      function function1 (a,b) {
          return a + b;
      }
      function function2 (a,b,c) {
          return function1(a,b) * c;
      }
      return {
          function1: function1,
          function2: function2,    
      }
    });