简体   繁体   English

无法从同一JS文件中的控制器中调用函数

[英]Can't call on a function from within a controller in the same JS file

My JS file looks like this, and I would like to use one of the function declared inside function(), inside the controller. 我的JS文件看起来像这样,我想使用控制器内部在function()内部声明的函数之一。

The file is being called when an HTML is uploaded. 上载HTML时正在调用该文件。

 (function() {
//Lots of different functions
})();

(function(angular) {
//Controller that uses a function declared above.
})(window.angular);

How do I do that? 我怎么做? When I'm simply stating the name of the function, it says "cannot file variable" - most likely because that function isn't loaded by the time the controller is initializing. 当我只是简单地说明函数的名称时,它说“无法文件变量”-最有可能是因为在控制器初始化时尚未加载该函数。

You simply created IIFE or immediate invoked function execution which is a technique that all developers use it to avoid defining variables or functions in the global scope, Because if you add anything without this iife 您只是创建了IIFE或立即调用的函数执行,这是一种技术,所有开发人员都可以使用它来避免在全局范围内定义变量或函数,因为如果添加任何内容时都没有此错误

(function(){}); // iife

it will be assigned to the global window object. 它将被分配给全局窗口对象。 that's why your controller can't call the function defined above. 这就是为什么您的控制器无法调用上面定义的函数的原因。 so you now have 2 different scopes first iife and the second iife 所以您现在有2个不同的范围,第一个和第二个

You can call function defined inside another function only if it is available to outer scope. 仅当外部范围可用时,才可以调用在另一个函数内部定义的函数。

function outer() { 
this.inner = function() {
    alert("hi");
}
} 

You can call outer function from within the controller by 您可以通过以下方式从控制器内部调用外部函数:

(new outer()).inner(); 

A couple of suggestions involving the same idea: 涉及相同想法的一些建议:

  1. Create the function outside of 在外部创建函数

     (function(angular) { //Controller that uses a function declared above. })(window.angular); 

    so that it's accessible from within that immediately invoked function AND from outside that immediately invoked function. 这样就可以从立即调用的函数内部以及从立即调用的函数外部访问它。

  2. When creating the function inside your controller, make it accessible to the outer scopes, perhaps by attaching it to window, eg window.yourFunction = function() { ... } . 在控制器内部创建函数时,可以通过将其附加到窗口(例如window.yourFunction = function() { ... }使其可用于外部作用域。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM