Call external js file function in Angular js controller

后端 未结 5 1960
挽巷
挽巷 2021-02-18 20:42

I have the external js file which has more functions.

I need to call these functions from angular controller.

For example: external.js



        
相关标签:
5条回答
  • 2021-02-18 20:52

    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 !

    0 讨论(0)
  • 2021-02-18 21:00

    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();
    
    0 讨论(0)
  • 2021-02-18 21:06

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

    0 讨论(0)
  • 2021-02-18 21:07

    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.

    0 讨论(0)
  • 2021-02-18 21:15

    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.

    0 讨论(0)
提交回复
热议问题