gpt4 book ai didi

javascript - 代码组织 AngularJS 巨大的 Controller

转载 作者:可可西里 更新时间:2023-11-01 02:54:01 25 4
gpt4 key购买 nike

我有一个巨大的 Controller ,我将它拆分成多个子 Controller ,然后根据它们的功能将它们放入其他文件中。

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

这是一个巨大的 Controller :

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

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

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
}
}

可以将函数作为参数发送吗?我是否可以不从子 Controller 返回任何东西,因为 $scope 监视一切? controller的一些功能用在另一个controller上可以吗?

现在我看到那不好而且不对,但我需要拆分主 Controller ,因为其中有超过 10k 行代码。

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

最佳答案

拥有 10,000 行代码的 Controller 尖叫您正在破坏 Single Responsibility Principle在您的代码中多次。

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

接下来,研究使用“Controller As” ' 语法,它允许您打破与 $scope 的联系。使用 $scope 是一个 anti-pattern ,因为很难确定直接放置在 $scope 上的项目来自何处、被使用和被修改。很容易发现一个对象的值不是你想要的,因为它在其他地方被修改了。来自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.

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

关于javascript - 代码组织 AngularJS 巨大的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28387912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com