How to call module factory from another module in Angular.js?

17,430

It is perfectly fine to use RequireJS and AngularJS together, however the term "module" has different meaning between the two and is a little bit confusing when it comes to dependencies.

In RequireJS a "module" is a typical Javascript file that encapsulates a piece of code. You define the dependencies using RequireJS in order to pass in/around other modules as dependencies and ensure correct script load ordering.

In AngularJS the term "module" specifically means an AngularJS "module", which is a container for a number of controller/services/directive etc. declarations.

You use RequireJS to define the order and dependencies of your script files. You then also need to tell Angular which "Angular modules" your module depends on, essentially importing all of the controllers/services/directives along with it.

In 'app/admin/app.admin' make sure you define the dependencies for your AngularJS module by passing in the 'app.admin.account.services' module as a second parameter e.g.

var app = angular.module('app.admin', ['app.admin.account.services']);

That will then import the 'app.admin.account.services' module into your main module making your providerService available for dependency injection.

Share:
17,430

Related videos on Youtube

Victor
Author by

Victor

Updated on June 04, 2022

Comments

  • Victor
    Victor almost 2 years

    I have problems with call a factory in one module from another module. I am using angular.js + require.js. Here is my code Module 1:

    define(['angular', 'app/admin/app.admin', 'app/admin/account/services'], function (angular, app, services) {
      app.controller('MainCtrl', ['$scope', 'providerService', function ($scope, providerService) {
        $scope.showMe = false;
        $scope.provider = providerService.Providers;
      }]);
    
    
      return app;
    });
    

    Module 2

    define(['angular', 'app/admin/config/index'], function (angular) {
      'use strict';
    
      var service = angular.module('app.admin.account.services', []);
    
      service.factory('providerService', ['app.admin.config',
        function (config) {
          var providers = [
            { name: 'google+', url: config.AUTH_URL + '/google' },
            { name: 'facebook', url: config.AUTH_URL + '/facebook' }
          ];
          return {
            Providers: providers
          };
        }
      ]);
    
      return service;
    });
    

    When i try to call providerService in module 2 from module 1. I got an error say providerService is not there. Can someone tell me what I did wrong here?

    Cheers

    • Joshua Clark
      Joshua Clark almost 11 years
      Where is the app module defined? It's not in this code. If you haven't already, then you need to declare app.admin.account.services and a dependency of app