我已经查看了分离文件的各种示例。我可以理解它们,但问题在于我的代码。我想在不同的文件中分开这些控制器。
'use strict';
angular.module('myModule', ['ui.bootstrap']);
var myApp = angular.module('myApp', []);
myApp.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
myApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.when('/getplaces', {
templateUrl: 'templates/getplaces.html',
controller: 'ListCtrl'
})
以下控制器需要位于不同的文件中。
///////////// MONTHLY DATA /////////////////////////////////////
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/getmonth', {
templateUrl: 'templates/getmacs.html',
controller: 'MonthlyCtrl'
})
}])
.controller('MonthlyCtrl', function ($scope, $http) { $scope.visible = true;
})
我有超过20个像上面这样的控制器。但我该如何分开它们。
答案 0 :(得分:4)
这是你应该怎么做的,
第一次声明
angular.module('appName', ['Module1', 'Module2', 'Service1']);
后续声明
这里所有控制器和服务都可以在单独的文件中。
angular
.module('Module1', [])
.controller('AbcController', ['$scope', '$timeout', 'Service1', function ($scope, $timeout, service1) {} ]);
angular
.module('Module2', [])
.controller('EfgController', ['$scope', '$timeout', 'Service1', function ($scope, $timeout, service1) {} ]);
angular.module('Service1', [])
.service('XYZService', ['$http', function LmnoService($http) {
} ]);
答案 1 :(得分:1)
这应该很容易完成,我会将我的应用程序路由配置组织到主app.js文件中。
myApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.when('/getplaces', {
templateUrl: 'templates/getplaces.html',
controller: 'ListCtrl'
}).when('/getmonth', {
templateUrl: 'templates/getmacs.html',
controller: 'MonthlyCtrl'
})
}])
然后,当您在每个文件中创建一个单独的控制器时,只需引用应用程序名称:
myApp.controller('MonthlyCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.visible = true;
}])
您还会注意到我正在使用数组初始化方法,这样可以在您进行缩小时为您节省一些时间。
答案 2 :(得分:1)
您可以遵循以下惯例:
angular, angular-routes etc
config
持有人js文件,其中包含您的模块声明。答案 3 :(得分:1)
我会将特定模块映射到功能(而不是按层),每个模块都包含其相关的控制器,服务和适当的指令。
例如,您将拥有一个名为“places.list”的模块,其中包含与之关联的所有控制器,服务/工厂和指令。
规则是:一个模块,一个文件,否则你将被迫按顺序声明这些文件......(第一个模块声明......然后是控制器......丑陋)
如果以正确的方式拆分模块,您会注意到每个模块都易于维护,并且通常不包含大量代码。
甚至每个路由声明(.config
)也会在这些模块之间分开。
=>所有关于地点的路线都将在模块places.list
中声明为
实际上,在主模块中声明整个导航规则会很难(并且难以维护)。
因此,通过仅加载与测试相关的特定模块的依赖性,可以容易地测试每个模块。