Can I have multiple functions in my AngularJS Factory?

ぃ、小莉子 提交于 2019-11-30 03:20:36
Abhijeet

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);

This is the service code:

myServices.factory('Auth', ['$resource',
  function($resource){
    return {
      Login: $resource(serviceURL + 'login', {}, { go: { method:'POST', isArray: false }}),
      Logout: $resource(serviceURL + 'logout', {}, { go: { method:'POST', isArray: false }}),
      Register: $resource(serviceURL + 'register', {}, { go: { method:'POST', isArray: false }}),
    };
  }
]);

And from my controller I just have to add the go() function call to make it work:

Auth.Login.go({ username: $scope.username, password: $scope.password },

I guess I could have named the go function after the method and called it "post()" instead for clarity...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!