22

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.

1
  • 1
    How have you imported the external js in the angular module? Commented Jan 21, 2015 at 19:59

5 Answers 5

10

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your response. I am newbie for angular js. if i put var external = require('assets/plugins/form-generation/js/external.js'); in controller means, i get this console error "ReferenceError: require is not defined".
i'm sorry, require is node.js only ... my mistake. ...still trying ;)
6

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

1 Comment

$window should be injected, for angular
1

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.

Comments

0

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 !

Comments

0

You need to create a global instance of the function.

Add a line:

var abc= new funcName(); at the end of the File and you can use this line (var abc= new funcName();) in your controller to invoke any methods from this file by using abc.methodName.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.