如何从角度js控制器中的另一个js文件调用全局函数

时间:2017-09-20 09:46:45

标签: javascript angularjs

我想创建一个包含常用功能的角度文件,我想在全局另一个角度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>

2 个答案:

答案 0 :(得分:0)

试试这个。希望它会对你有所帮助。

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

});

答案 1 :(得分:0)

您好请参考以下代码并运行

检查我如何在myApp模块

中添加SocietyApp的依赖关系

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>