简体   繁体   中英

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.

The file is being called when an HTML is uploaded.

 (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

(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

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() { ... } .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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