gpt4 book ai didi

angularjs - 为什么全局函数在 Angular 1.3 中被认为是 "wrong"

转载 作者:行者123 更新时间:2023-12-01 23:49:35 25 4
gpt4 key购买 nike

传统上我是这样管理我的 Angular 代码的

//File 1
angular.module('name',[])
//File 2
function TestController(){

}
TestController.prototype.// inherited stuff
angular.module('name').controller('testController',TestController);

这非常有效,让我可以轻松地对文件进行分区。现在我尝试升级到 1.3 并获得臭名昭着的...

Error: [ng:areq] Argument 'TestController' is not a function, got undefined 

当然这是由于this change它声称希望清理人们编写代码的方式。这个模式更复杂吗?有没有办法在不更改全局设置的情况下保持这种模式?

最佳答案

实际上有一个comment on the page you linked对此有一个相当可靠的解释。

Global controllers refer to your controllers being defined as function on the window object. This means that they are openly available to conflict with any other bit of JavaScript that happens to define a function with the same name. Admittedly, if you post-fix your controllers with ...Controller then this could well not happen but there is always the chance, especially if you were to use a number of 3rd party libraries. It is much safer to put these controller functions inside the safety of a module. You then have more control over when and where this module gets loaded. Unfortunately controller names are global across an individual Angular app and so you still have the potential for conflict but at least you can't clash with completely different code in the JavaScript global namespace.

所以这个想法是全局 Controller 函数可能与您使用的任何 javascript 中的任何其他全局函数冲突。因此,为了消除与您自己的代码或第三方脚本发生冲突的可能性,不使用全局 Controller 会使您的代码更安全、更一致。

正如@Brett 在评论中提到的那样,您可以在原型(prototype)制作过程中使用 IIFE。 Here is an update of your plunk that uses that .主要变化如下所示。

(function() {
TestController.prototype.name = 'World'
})();

关于angularjs - 为什么全局函数在 Angular 1.3 中被认为是 "wrong",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27232551/

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