繁体   English   中英

如何从Angular JS控制器中的另一个JS文件中调用全局函数

[英]How to call global function from another js file in angular js controller

我想创建一个包含通用功能的角度文件,并且希望在全局的另一个角度javascript文件中调用它们,

 //code in first.js file var app = angular.module("myapp", []); app.service("myservice", function () { return { func1: function () { alert("function in another file") } }; }); //code in second.js /// <reference path="first.js" /> var SocMaster = angular.module("SocietyApp", []); SocMaster.controller("MsSocietyCntrl", function ($scope, $http,myservice) { $scope.callFoo = function () { myservice.func1(); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

尝试这个。 希望对您有帮助。

var app = angular.module("myapp", []);
app.service("myservice", function () {
   this.func1 = function () {
        return alert("function in another file");
    }

});

嗨,请参考下面的代码并运行它

检查我如何在SocietyApp模块中添加myApp依赖关系

 var app = angular.module("myapp", []); app.service("myservice", function () { this.func1= function () { alert("function in another file") } }); //code in second.js /// <reference path="first.js" /> var SocMaster = angular.module("SocietyApp", ['myapp']); SocMaster.controller("MsSocietyCntrl", function ($scope, $http,myservice) { $scope.callFoo = function () { myservice.func1(); } }); 
 <html > <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script> </head> <body ng-app='SocietyApp'> <div ng-controller='MsSocietyCntrl'> <button ng-click="callFoo()">Click</button> </div> </body> </html> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM