Search code examples
javascriptangularjsangularjs-scopeangular-ui-router

Loading multiple modules or controllers in Angular is not working


I am needing to "import" or "use" a Modal Service and my current code that works looks like this

angular
    .module("deviceManagement")
    .controller("DeviceDetailCtrl",
    ["$scope",
        "$http",
        "$stateParams",
        "deviceService",
        DeviceDetailCtrl]);

So I know that there is a file angularModalService.js in which it contains

var module = angular.module('angularModalService', []);
module.factory('ModalService', ...................

With those things in mind I want to "inject" this "ModalService" into my current code, but it says "undefined" etc..

Above my current code I was trying both of these ways of setting another module, but i'm not sure if i should be setting a module or a controller or both

  var app2 = angular.module('app2', ['angularModalService']);

Or ..

angular
    .module("app2", ['angularModalService'])
    // .controller ??? 

Solution

  • Jeremy, there are some things to noted.

    1. If you want to use another module as the dependency of your module. You need to inject it into your module. In your case, your code will be.

    angular.module('app2', ['angularModalService']);

    Note that it is equivalent to

    var application2 = angular.module('app2', ['angularModalService']);
    

    The different is you can config your module in the future by two ways.

    angular.module('app2').config(...)
    application2.config(...)
    
    1. And if you want to use the factory ModalService in your app2, just inject it into your controller.

    angular.module('app2').controller('SomeController', ['ModalService', function(ModalService) { //TODO }]);

    Seem you still confusing about angular module. Please read this article. Quoted

    var myModule = angular.module('myModule', []);
    
    // add some directives and services
    myModule.service('myService', ...);
    myModule.directive('myDirective', ...);
    
    // overwrites both myService and myDirective by creating a new module
    var myModule = angular.module('myModule', []);
    
    // throws an error because myOtherModule has yet to be defined
    var myModule = angular.module('myOtherModule');