Can I have multiple functions in my AngularJS Factory?

SomethingOn picture SomethingOn · Feb 17, 2014 · Viewed 23.6k times · Source

I'm following the Tutorial from the official AngularJS docs and I want to know if I can add another function to the Phone factory so that I can organize code better. They have declared a "query" function, but what if I wanted to add a query2 function that references a different url...say phones2/:phoneName.json for example?

Factory declaration:

var phonecatServices = angular.module('phonecatServices', ['ngResource']);

phonecatServices.factory('Phone', ['$resource',
  function($resource){
    return $resource('phones/:phoneId.json', {}, {
      query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
    });
  }]);

I have tried a number of things and non of them seem to be working :s

This answer seems to be on the right track, but the syntax for each factory function doesn't quite match up with the above factory.

Something along the lines of:

phonecatServices.factory('Phone', ['$resource',
      function($resource){
       return {
        query: ...
        query2: ...
       }
      }]);

Answer

Abhijeet picture Abhijeet · Apr 6, 2015

One such example of this is: Link for Demo

angular.module('services', []).factory('factoryName', ["$filter",
  function($filter) {
    var method1Logic = function(args) {
      //code
    };
    var method2Logic = function(args) {
     //code
    };
    return {
      method1: method1Logic,
      method2: method1Logic
    };
  }
]).controller('MainController', ["$scope", "$rootScope", "$filter", "factoryName", function ($scope, $rootScope, $filter,factoryName) {
     $scope.testMethod1 = function(arg){
       $scope.val1 = factoryName.method1(arg);
     };

     $scope.testMethod2 = function(arg){
       $scope.val2 = factoryName.method2(arg);
     };
}]);

There is even a better version Opinionated version of this: References

function AnotherService () {

  var AnotherService = {};

  AnotherService.someValue = '';

  AnotherService.someMethod = function () {

  };

  return AnotherService;
}
angular
  .module('app')
  .factory('AnotherService', AnotherService);