-->

AngularJS Modules and External Controllers

2019-06-04 16:31发布

问题:

I have a page containing multiple containers. Each container will have its own controller but point to one factory, which handles all the logic interacting with a web service API. I would like to have a separate file for each controller BUT I want all of this inside of one module. for the life of me I cannot find how to include controllers from different files into one modules.

//file 1
MyController ....

//file 2
MyOtherController

//file 3
MyFactory

//file 4
The Module

The module would be composed of MyController, MyOtherController and MyFactory defined in three separate files. Can someone help with this or point me to a good resource? Thanks!

回答1:

You can think of a module as a container for the different parts of your app – controllers, services, filters, directives, etc. To access a container just call its module name for example

//file.4

angular.module("theModule",[]);

now that you have declared main module within angular now you can access mainModule from anywhere using angular

//file 1

angular.module("theModule").controller("MyController",[function(){...}]);

//file 2

angular.module("theModule").controller("MyOtherController",[function(){...}]);

//file 3

angular.module("mainModule").factory("MyFactory",[function(){...}]);

Check out the documentation for more information.

I also suggest reading Google's style guide and conventions manual

Also read about setting up app structure for maintainability



回答2:

Here is a example of an Angular module setup I am using in an app that allows a separate external file for each module type. Note that the app must load before the external files. Tested on Angular 1.4.9.

Index.html

<script src="bower_components/angular/angular.min.js"></script>
<script src="js/ng-app.js"></script>
<script src="js/ng-factories.js"></script>
<script src="js/ng-directives.js"></script>
<script src="js/ng-controllers.js"></script>

ng-app.js

var app = angular.module('myApp', [
    'factories',
    'directives',
    'controllers'
]);

ng-controllers.js

//note: I am injecting the helloFac factory as an example
var ctrl = angular.module('controllers', []);

ctrl.controller('MyCtrl', ['$scope', 'helloFac', function($scope, helloFac) {
    console.log(helloFac.sayHello('Angular developer'));
}]);

ng-directives.js

angular.module('directives',[])
    .directive('test', function () {
        return {
            //implementation
        }
    })
    .directive('test2', function () {
            return {
                //implementation
            }
    });

ng-factories.js

var factories = angular.module("factories", []);

factories.factory('helloFac', function() {
    return {
        sayHello: function(text){
            return 'Hello ' + text;
        }
    }
});