一个“工厂”对象中的多个AngularJS工厂

时间:2015-11-18 18:10:03

标签: angularjs controllers angularjs-factory factories

我希望通过制作一个可以执行多项操作的工厂对象列表,使我的工厂与制作控制器的方式相同。在EX1中(参见下面的代码),我想定义多个工厂并将它们全部存储在一个“工厂”对象中,并将“工厂”对象列表传递给我的控制器。就像我在EX2中一样,我定义了一个“控制器”对象,它保存我的控制器并将其传递给我的demoApp.controllers。当我尝试做我在下面发布的内容时,我得到了这个: 错误:[$ injector:unpr] http://errors.angularjs.org/1.3.14/ $ injector / unpr?p0 = factoriesProvider%20%3C-%20factories%20%3C-%20SimpleController

我不知道为什么。请帮忙!我会给你一些布朗尼点。

如果有办法做到这一点,我可以通过一个'factories.js'文件隔离我的代码,这个文件将容纳我的所有工厂,另一个文件,'controllers.js'文件,它包含我的所有控制器,这会简化我的代码。

EX1:

var factories = {};
factories.simpleFactory = function($http){
   var customers = [
      {name: "John Smith", city: "Phoenix"},
      {name: "John Doe", city: "New York"},
      {name: "Jane Doe", city: "San Francisco"}
    ];
   var factory = {};
   factory.getCustomers = function(){
      return customers;
    };

  return factory;
}
factories.notSimpleFactory= function($http){
   var someVariable = [1,2,3,4];
   var factory2 = {};
   factoryTwo.getSomeVariable() = function(){
       return someVariable;
   }
   return factory2;
}
demoApp.factory(factories);

EX2

var controllers = {};

controllers.SimpleController = function($scope,factories)
{
  $scope.customers= {}
  $scope.factory2Var = {}
  init();
  function init(){
    $scope.customers = factories.simpleFactories.getCustomers();
  }
  callNotSimpleFactory()
  function callNotSimpleFactory(){
       $scope.factory2Var = factories.notSimpleFactory.getSomeVariable(); 
  } 
   $scope.addCustomer= function(){
$scope.customers.push({name: $scope.newCustomer.name, city: $scope.newCustomer.city});
}};
demoApp.controller(controllers);

1 个答案:

答案 0 :(得分:2)

最后使用它 控制器如bleow和工厂相同

for (var prop in controllers) {
    demoApp.controller(prop, controllers[prop]);
}