Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call external js file function in Angular js controller

Tags:

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.

like image 680
user2731645 Avatar asked May 16 '14 14:05

user2731645


People also ask

How do you call a function in an external JavaScript file?

Calling a function using external JavaScript file Js) extension. Once the JavaScript file is created, we need to create a simple HTML document. To include our JavaScript file in the HTML document, we have to use the script tag <script type = "text/javascript" src = "function.

Can I call a JS function from another JS file?

Answer: Use the export and import Statement Since ECMAScript 6 (or ES6) you can use the export or import statement in a JavaScript file to export or import variables, functions, classes or any other entity to/from other JS files.

Can we call function from another controller in AngularJS?

If the two controller is nested in One controller. Then you can simply call: $scope. parentmethod();


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

like image 111
nilsK Avatar answered Oct 14 '22 15:10

nilsK


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();
like image 34
Kshitij Avatar answered Oct 14 '22 15:10

Kshitij