我正在使用 angular-seed用于构建我的应用程序的模板。最初,我将所有 JavaScript 代码放入一个文件 main.js
。该文件包含我的模块声明、 Controller 、指令、过滤器和服务。该应用程序像这样运行良好,但随着我的应用程序变得越来越复杂,我担心可扩展性和可维护性。我注意到 angular-seed 模板中的每一个都有单独的文件,所以我试图将我的代码从单个 main.js
文件分发到标题中提到的每个其他文件中这个问题在angular-seed的app/js
目录下找到模板。
我的问题是:如何管理依赖关系以使应用程序正常工作?现有文档找到here在这方面不是很清楚,因为给出的每个示例都显示了一个 JavaScript 源文件。
我的一个例子是:
应用程序.js
angular.module('myApp',
['myApp.filters',
'myApp.services',
'myApp.controllers']);
Controller .js
angular.module('myApp.controllers', []).
controller('AppCtrl', [function ($scope, $http, $filter, MyService) {
$scope.myService = MyService; // found in services.js
// other functions...
}
]);
过滤器.js
angular.module('myApp.filters', []).
filter('myFilter', [function (MyService) {
return function(value) {
if (MyService.data) { // test to ensure service is loaded
for (var i = 0; i < MyService.data.length; i++) {
// code to return appropriate value from MyService
}
}
}
}]
);
服务.js
angular.module('myApp.services', []).
factory('MyService', function($http) {
var MyService = {};
$http.get('resources/data.json').success(function(response) {
MyService.data = response;
});
return MyService;
}
);
主.js
/* This is the single file I want to separate into the others */
var myApp = angular.module('myApp'), []);
myApp.factory('MyService', function($http) {
// same code as in services.js
}
myApp.filter('myFilter', function(MyService) {
// same code as in filters.js
}
function AppCtrl ($scope, $http, $filter, MyService) {
// same code as in app.js
}
如何管理依赖项?
提前致谢。
最佳答案
问题是由于您在所有单独的文件中“重新声明”您的应用程序模块引起的。
这是应用程序模块声明(不确定声明是否正确)的样子:
angular.module('myApp', []).controller( //...
这就是您的应用程序模块的赋值(也不确定赋值是否正确)的样子:
angular.module('myApp').controller( //...
注意缺少方括号。
所以,前一个版本,带有方括号,应该只使用一次,通常在您的 app.js
或 main.js
。所有其他相关文件 - Controller 、指令、过滤器 ...... - 应该使用后一个版本,没有方括号。
我希望这是有道理的。干杯!
关于javascript - AngularJS 种子 : putting JavaScript into separate files (app. js、controllers.js、directives.js、filters.js、services.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16771812/