Amir A.Eitan
Amir A.Eitan

Reputation: 193

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.

Upvotes: 0

Views: 74

Answers (3)

therobinkim
therobinkim

Reputation: 2568

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

Upvotes: 0

Mohammed Ramadan
Mohammed Ramadan

Reputation: 723

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

Upvotes: 1

PathToMotivation
PathToMotivation

Reputation: 5

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(); 

Upvotes: 0

Related Questions