Home » Angularjs » Call external js file function in Angular js controller

Call external js file function in Angular js controller

Posted by: admin November 30, 2017 Leave a comment

Questions:

I have the external js file which has more functions.

I need to call these functions from angular controller.

For example: external.js

...
...
function fun() {
  ...
  ...
}
...
...

Controller: acccountController.js

myApp.controller('AddAccountController',function ($scope,AddAccountLoginServices,$location,localStorageService,$compile,toaster){
   ....
   ....

   $scope.getLoginForm = function(siteId,name) { 
            ...
            ...
            fun(); // This function from external.js file
   });

   ...
   ...

});

I have imported external.js before the acccountController.js. But it doesnt calling that function. And also i have not get any console error for this.

How to achieve this… Thanks in advance.

Answers:

EDIT: gave wrong answer, my bad. the following example works.

your external file should like this:

var doSomething = (function () {
  "use strict";
   return {
      test: (function () {
        return 'test';
      }()),
      test2: (function () {
        return console.log('test 2');
      })
   };
}());

and in your controller you call your scripts function:

console.log(doSomething.test);

or

doSomething.test2();

i learned something too, thanks 😉

Questions:
Answers:

As mentioned by @nilsK, you define a self invoking function. And then reference to it via window object. For example –

(function functionName(){
    Do Something Here...
})();

And then,

window.functionName();

And if your are using AngularJS,

$window.functionName();

Questions:
Answers:

I have similar situation and I did not have to make it self invoking function. Including the external js file into the html and it worked fine.

Questions:
Answers:

Where is you call $scope.getLoginForm()?. I think you never call it. So fun() is not called, so you not see any thing. You need call $scope.getLoginForm(). Two way to call
In HTML <button ng-click="getLoginForm()"></button>
Or in Javascript $scope.getLoginForm()
Good luck !