当前位置: 动力学知识库 > 问答 > 编程问答 >

AngularJS controller and service creation

问题描述:

Im working on a new Angular project with the following files:

//app.js

var mainApp = angular.module('mainApp', ['serviceA', 'serviceB', "ctrlA", 'ctrlB']);

//ctrlA.js

var ctlA = angular.module('serviceA', []);

ctlA.controller('menuController', ['$scope', 'serviceA', function($scope, serviceA) {

// ...

}]);

Is there a reason not to do it this way ?

//ctrlB.js

angular.module('mainApp')

.controller('ctrlB', ['$scope', 'serviceA', function($scope, serviceA) {

// ...

}]);

网友答案:

What Zenorbi, mentioned is absolutely right. However, thought of adding this information to conclude a better answer.

You can modularize the app into multiple segments to make it easy to understand. The segmentation can be done in different ways.

Based on service types - this will be useful for small applications

var mainApp = angular.module('mainApp', [
    'app.controllers',      // Controllers
    'app.directives',       // Directives
    'app.filters',          // Filters
    'app.services'          // Services
]);

Example implementation of a module.

var ctrls = angular.module('app.controllers');
ctrls.controller('menuController', ['$scope', 'serviceA', function($scope, serviceA) {
  // ...
}]);

According to the purpose of each module. For example, you can separate chart related classes to a separate module and isolate it from the main code base. This will allow parallel programming by someone else, as this module can act independent from the parent module.

网友答案:

Both implementations are valid, but the module system is there to make sure you separate a bigger application into modules. If serviceA, serviceB, ctrlA and ctrlB are closely related, you might as well bundle them into a module. If you want to have your services elsewhere, you may create a module called mainApp.services.

It is up to you, how you structure the code, but modules exist for a reason. To have more than one "thing" in them.

分享给朋友:
您可能感兴趣的文章:
随机阅读: