问题
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