本文介绍了如何从另一个脚本(AngularJS)调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题的简化版本.假设我有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脚本,而不是从loadMe.js脚本调用CallMe函数并返回该函数返回的内容,在这种情况下为数组[1,2] ,3].谢谢!

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)调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 13:30