将AngularJS控制器拆分为多个文件

时间:2016-05-11 14:45:35

标签: javascript angularjs node.js

我有一个使用Onsen UI和AngularJS构建的跨平台企业应用程序。但是,该应用程序的规模正在快速增长,并且变得令人困惑且难以管理。到目前为止,我已经能够管理1个app.js文件中的所有应用程序控制器,并且该应用程序运行正常。但我想将我的控制器分成不同的.js文件,例如login.js,registration.js。随着应用程序的增长,使其更易于管理。

我在SO上找到了THIS解决方案(标记答案),但我无法实现它。同样, @ jason328 在链接上的答案看起来非常优雅,但我再次陷入使用我的代码实现这一点。

在我的主要新 app.js 文件中,我有以下模块:

angular.module('myApp.controllers', ['onsen']);

然后在例如 login.js 我按以下方式设置了我的模块:

angular.module('myApp.controllers').controller('LoginController', ['$scope', '$http', function($scope, $http)
{
    // All the login logic goes here
}]);

这不起作用,因为没有显示任何页面。当我在原始 app.js 文件中进行此设置时,该应用程序运行正常(下面的原始代码)。

var app = angular.module("myApp", ['onsen']);
// Manages the state of the login.html screen
app.controller("LoginController", function($scope, $http)
{
    // All the login logic goes here
});

我的问题在于我认为新app.js中的 [' onsen'] ?但是我如何将其包含在我试图实现的 SO 解决方案中?

2 个答案:

答案 0 :(得分:1)

还有另一种方法可以做到这一点。您可以为每个文件创建一个模块,并将它们添加到myApp模块,如下所示:

app.js

var app = angular.module("myApp", ['onsen', 'loginControllers', 'otherController']);

login.js

var login = angular.module("loginControllers", []);
login.controller("LoginController", function($scope, $http)
{
    // All the login logic goes here
});

other.js

var other = angular.module('otherControllers', []);
other("OtherController", function($scope, $http)
{
    // All the other logic goes here
});

确保已将所有脚本添加到index.html。

答案 1 :(得分:0)

您可以将它们转换为模块,例如@nicous,并在需要使用它们的地方将其导入到主app.js中,然后可以使用webpack或任何其他捆绑程序为您生成捆绑包。这样,您无需将所有文件都添加到html文件中。

相关问题