2016-06-08 47 views
1

我想知道是否有可能使用其他工厂功能中的工厂内的功能以及如何。我试过了,但是它表示这个函数并不存在。例如,我有这个工厂:试图访问另一个内部工厂功能

.factory("SyncService", function($q, $http, ...){ 
    return { 
     function1: function(){ 
       //Do function1 things 
       }, 
     function2: function(){ 
       //Here I want to call function1 
       } 
      } 
    } 

所以在这个例子中,可以调用函数2中的function1?

+0

谢谢大家。你们都帮助过我,但我只将你的答案标记为我的最爱,尽管我喜欢他们。 –

回答

2

,你可以通过重新构造你编写你的服务的方式..这里是一个最佳实践您:

.factory("SyncService", function($q, $http, ...){ 

    var fun = function(){ 
       //Do function1 things 
       }; 
    var anotherFun = function(){ 
       fun(); 
       }; 
    var service { 
     function1: fun , 
     function2: anotherFun 
      } 
    }; 

    return service; 

} 
+0

问题是,功能** fun **也必须在外面调用。为了达到这个目的,我应该这样称呼它:** SyncService.function1 ** 对不起,如果我的问题是基本的,但我不明白这些工厂功能非常好:P –

+0

是的,从控制器你会调用'SyncService.function1()' –

+0

这是推荐的方法:https://github.com /johnpapa/angular-styleguide/blob/master/a1/README.md#factories –

1

您可以使用 this.function1();

.factory("SyncService", function($q, $http, ...){ 
    return { 
     function1: function(){ 
       //Do function1 things 
       }, 
     function2: function(){ 
       this.function1(); 
       } 
      } 
} 
1

你当然可以从另一个调用工厂函数工厂函数。

的Index.html

<html> 

    <head> 
    <script data-require="[email protected]*" data-semver="1.5.6" src="https://code.angularjs.org/1.5.6/angular.min.js"></script> 
    <script data-require="[email protected]*" data-semver="1.0.0-alpha.5" src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.0-alpha.5/angular-ui-router.js"></script> 
    <link rel="stylesheet" href="style.css" /> 
    <script src="factory.js"></script> 
    <script src="controller.js"></script> 

    </head> 

    <body ng-app="myApp" ng-controller="myCtrl"> 
    <h1>Hello Plunker!</h1> 
    </body> 

</html> 

Facotory.js

angular.module('myApp',[]) 
    .factory('myFactory',function(){ 
    var obj = {}; 
    obj.myFunction1 = function(){ 
     this.myFunction2(); 
    } 
    obj.myFunction2 = function(){ 
      alert("HEY!"); 
    }  

    return obj; 

    }); 

Controller.js

angular.module('myApp') 

    .controller('myCtrl',function($scope,myFactory){ 

    myFactory.myFunction1(); 

    }) 

这里是工作plunker https://plnkr.co/edit/SZV7i97WJHw7LDhIjyzW?p=preview