[英]Call external js file function in Angular js controller
I have the external js file which has more functions.我有具有更多功能的外部js文件。
I need to call these functions from angular controller.我需要从角度控制器调用这些函数。
For example: external.js例如: external.js
...
...
function fun() {
...
...
}
...
...
Controller: acccountController.js控制器: accountController.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.我在 acccountController.js 之前导入了 external.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.如何实现这一点......提前致谢。
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 .正如@nilsK 所提到的,您定义了一个自调用函数。 And then reference to it via window
object.然后通过window
对象引用它。 For example -例如 -
(function functionName(){
Do Something Here...
})();
And then,进而,
window.functionName();
And if your are using AngularJS,如果您使用的是 AngularJS,
$window.functionName();
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.将外部 js 文件包含到 html 中,效果很好。
Where is you call $scope.getLoginForm()?.你在哪里打电话 $scope.getLoginForm()? I think you never call it.我想你永远不会打电话给它。 So fun() is not called, so you not see any thing.所以 fun() 没有被调用,所以你看不到任何东西。 You need call $scope.getLoginForm().您需要调用 $scope.getLoginForm()。 Two way to call In HTML <button ng-click="getLoginForm()"></button>
Or in Javascript $scope.getLoginForm()
Good luck !两种调用方式在 HTML <button ng-click="getLoginForm()"></button>
或在 Javascript $scope.getLoginForm()
祝你好运!
You need to create a global instance of the function.您需要创建该函数的全局实例。
Add a line:添加一行:
var abc= new funcName(); 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.在文件的末尾,您可以在控制器中使用这一行 (var abc= new funcName();) 通过使用 abc.methodName 调用该文件中的任何方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.