代码组织 AngularJS 庞大的控制器

Code organization AngularJS huge controller

我有一个巨大的控制器,我把它分成了子控制器,我根据它们的功能放入其他文件中。

一切正常,但我需要关于我的问题的建议和答案: 我做对了吗?

这是一个巨大的控制器:

function controller($scope, $http) { 
  //code
  someFunction($scope, boolA, function1, function2);
  //code
}

这是我在其他文件中的子控制器的代码,我在前端控制器之后加载它:

function someFunction($scope, boolA, function1, function2) {
  //code where I use all the parametrs of function
  function someFunctionSubcontoller() {
    //here is used another function from other subcontroller
  }
}

可以将函数作为参数发送吗?我是否可以不 return 来自子控制器的任何东西,因为 $scope 监视一切? contoller的一些功能用在另一个contoller里可以吗?

现在我看到不好不对,但我需要拆分主控制器,因为有超过 10k 行里面有代码。

感谢您的建议和帮助!!!

我建议您在编写代码时使用 angular.module()。我会很好地分离你的代码并模块化。

您可以创建一个子控制器并使用 $controller 依赖项将其注入主控制器。

var app = angular.module('myApp',[]);

app.controller('subCtrl', function(){
   $scope.test3 = function(){
     //code
   };
   $scope.test4 = function(){
     //code
   };
});

app.controller('ParentCtrl', function($scope, $controller){
   //injecting subCtrl scope inside ParentCtrl
   $controller('subCtrl', {$scope: $scope});
   //after this line method and $scope variables of subCtrl will be available.
   $scope.test = function(){
     //code
   };
   $scope.test2 = function($scope){
     //code
   };
});

具有 10,000 行代码的控制器尖叫您在代码中多次违反Single Responsibility Principle

与其制作“子控制器”,不如考虑首先重构您的代码并将可重用的代码段移动到服务中。然后,在您的 UI 中寻找可以转换为指令的通用组件,并使用隔离范围将一些逻辑移动到这些指令的控制器中。你会发现当这些元素自己负责时,控制和测试这些元素会容易得多。

接下来,研究使用 'Controller As' Syntax, which allows you to break your ties with $scope. Using $scope is an anti-pattern, since it is very difficult to identify where items placed directly on $scope originate from, are used, and are modified. It is very easy to find that an object has a value other than what you intended because it was modified somewhere else. From the Angular Documentation:

•Using controller as makes it obvious which controller you are accessing in the template when multiple controllers apply to an element.

•If you are writing your controllers as classes you have easier access to the properties and methods, which will appear on the scope, from inside the controller code.

•Since there is always a . in the bindings, you don't have to worry about prototypal inheritance masking primitives.

最重要的是,您可能会发现,如果您重构代码而不只是“分解代码”,您最终会得到一个更易于管理、更可测试且更可靠的解决方案。