AngularJS Modules and External Controllers

走远了吗. 提交于 2019-12-01 13:27:28

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

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;
        }
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!