我的 AngularJS Factory 中可以有多个函数吗? [英] Can I have multiple functions in my AngularJS Factory?

查看:21
本文介绍了我的 AngularJS Factory 中可以有多个函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注官方 AngularJS 文档中的 教程,我想知道我可以向电话工厂添加另一个功能,以便更好地组织代码.他们已经声明了一个查询"函数,但是如果我想添加一个引用不同 url 的 query2 函数怎么办……例如,phones2/:phoneName.json?

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?

工厂声明:

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

我尝试了很多东西,但似乎都没有效果:s

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.

大致如下:

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

推荐答案

这样的一个例子是:演示链接

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

这篇关于我的 AngularJS Factory 中可以有多个函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆