title: Angular: Adding factory methods on module from within run() function
body: <p>I have an angular module with a factory that returns a resource based on inputs from a constant on that same module.</p>
  
  <p>like so:</p>
  
  <pre><code>angular.module('resources', [])
      .constant('resourceMap', { 
          resource1: { ... },
          resource2: { ... },
          resource3: { ... },
          ...
      })
      .factory('resourcebuilder', function($resource) {
          return {
              build: function(resourceData) {
                  return $resource(resourceData);
              }
          };
      });
  </code></pre>
  
  <p>I then can create factories that return those resources like so:</p>
  
  <pre><code>angular.module('resources')
      .factory("resource1" function(resourceMap, resourceBuilder) {
          return resourceBuilder.build(resourceMap["resource1"]);
      })
      .factory("resource2" function(resourceMap, resourceBuilder) {
          return resourceBuilder.build(resourceMap["resource2"]);
      })
      .factory( ...
  </code></pre>
  
  <p>But, I want to be able to loop through the keys in ResourceMap and create a factory for the resource on each iteration. I tried putting it in the run function like:</p>
  
  <pre><code>.run(function(resourceMap, resourceBuilder) {
      for (res in resourceMap) {
          angular.module('resources')
              .factory(res, function(resourceMap, resourceBuilder) {
                  return resourceBuilder.build(resourceMap[res]);
              });
      };
  });
  </code></pre>
  
  <p>but this doesn't work. Does anybody know how I can do this?    </p>
  
  <p>The issue doesn't have anything to do with the resource function. basically I need to figure out a way to add factories to a module from within some sort of factory/service on that same module.  </p>
  
  <p><strong>edit:</strong> </p>
  
  <p>I tried creating another module that injects the resources module as a dependency and uses angular.foreach to loop through the resourceMap and create factories like this:</p>
  
  <pre><code>var resourceProvider = angular.module("resourceProvider", ['resources'])
  resourceProvider.run(function(resourceBuilder, resourceMap) {
      angular.forEach(resourceMap, function(val, key) {
          resources.factory(key, function(resourceBuilder, resourceMap) {
              return resourceBuilder.build(val);
          });
      });
  });      
  </code></pre>
  
  <p>this is still giving me an error as it doesn't not seem to be properly creating the factories on the resources module.</p>