How to call function from another script (AngularJS)

混江龙づ霸主 提交于 2019-12-23 02:47:11

问题


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];
}

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!


回答1:


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]

});

Don't forget to include the module in your HTML

<script src="/assets/js/models/loadMe.js"></script>

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;

Then in your view you can use {{loadMe.callMe()}}



来源:https://stackoverflow.com/questions/36988823/how-to-call-function-from-another-script-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!