Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 277
Victor Avatar asked May 22 '13 03:05

Victor


1 Answers

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.

like image 75
Brett Postin Avatar answered Oct 26 '22 12:10

Brett Postin