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.
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.
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.
If the two controller is nested in One controller. Then you can simply call: $scope. parentmethod();
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 ;)
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With