2

我有一个包含多个容器的页面。每个容器都有自己的控制器,但指向一个工厂,该工厂处理与 Web 服务 API 交互的所有逻辑。我想为每个控制器创建一个单独的文件,我希望所有这些都在一个模块中。在我的一生中,我找不到如何将不同文件中的控制器包含到一个模块中。

//file 1
MyController ....

//file 2
MyOtherController

//file 3
MyFactory

//file 4
The Module

该模块将由三个单独的文件中定义的 MyController、MyOtherController 和 MyFactory 组成。有人可以帮助解决这个问题或为我指出一个好的资源吗?谢谢!

4

2 回答 2

4

您可以将模块视为应用程序不同部分的容器 - 控制器、服务、过滤器、指令等。要访问容器,只需调用其模块名称即可

//文件.4

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

现在您已经在 Angular 中声明了主模块,现在您可以使用 Angular 从任何地方访问 mainModule

//文件1

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

//文件2

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

//文件3

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

查看文档以获取更多信息。

我还建议阅读 Google 的样式指南和约定手册

另请阅读有关设置应用程序结构以实现可维护性的信息

于 2014-08-27T03:59:31.657 回答
1

这是我在应用程序中使用的 Angular 模块设置示例,该应用程序允许为每种模块类型使用单独的外部文件。请注意,应用程序必须在外部文件之前加载。在 Angular 1.4.9 上测试。

索引.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;
        }
    }
});
于 2016-01-21T20:03:13.367 回答