AngularJS Modules and External Controllers

后端 未结 2 2143
轻奢々
轻奢々 2021-01-15 05:26

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 servic

相关标签:
2条回答
  • 2021-01-15 05:59

    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;
            }
        }
    });
    
    0 讨论(0)
  • 2021-01-15 06:08

    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

    0 讨论(0)
提交回复
热议问题