问题描述
这是我的问题的简化版本.假设我有 loadMe.js
脚本,其中包含返回一些数组的简单函数.
Here is the simplified version of my problem.Let's say that I have loadMe.js
script containing simple function which is returning some array.
CallMe = function(){
return [1,2,3];
}
是否有可能在 ng
中创建另一个脚本来加载 loadMe.js
脚本,而不是从 调用
脚本并返回该函数返回的任何内容,在本例中为数组 [1,2,3].谢谢!CallMe
函数loadMe.js
Is there any possibility in ng
to create another script which will load loadMe.js
script , than invoke CallMe
function from loadMe.js
script and return whatever that function is returning, in this case array [1,2,3].Thank You!
推荐答案
将 loadMe.js 变成一个模块,如:
Make loadMe.js into a module like:
var loadMe = angular.module('loadMe',[]);
loadMe.factory('loadMe', [function(){
return {
'callMe':function(){
return[1,2,3];
}
}]);
然后将模块注入您的应用程序:
Then inject the module into your app:
var myApp = angular.module('myApp', ['loadMe']);
然后在您的控制器中使用它:
Then use it in your controller:
myApp.controller('mainController', ['$scope', 'loadMe', function ($scope, loadMe) {
//use loadMe to get [1,2,3]
var array = loadMe.callMe();
console.log(array); //will log [1,2,3]
});
不要忘记在 HTML 中包含该模块
Don't forget to include the module in your HTML
<script src="/assets/js/models/loadMe.js"></script>
如果您想直接从您的视图中获取数组,您可以将您的 loadMe 模块添加到控制器的作用域中:
If you are looking to get the array directly from your view you can add your loadMe module to the controller's scope:
$scope.loadMe = loadMe;
然后在您的视图中您可以使用 {{loadMe.callMe()}}
Then in your view you can use {{loadMe.callMe()}}
这篇关于如何从另一个脚本调用函数(AngularJS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!