[英]How can I call AngularJS function in JS function
This is the first interaction with angularjs. 这是与angularjs的第一次互动。 it's first time. 这是第一次。 how can I call the function and get the items now in another controlers ? 我怎样才能调用该功能并在另一个控制器中获取这些物品?
I am loading CSV file using AngularJS 我正在使用AngularJS加载CSV文件
var Mymodule = angular.module('Mymodule', []);
Mymodule.factory('Items', ['$http', function($http){
var Url = "data/ex.csv";
var Items = $http.get(Url).then(function(response){
return csvParser(response.data);
});
return Items;
}]);
I need to get returned values to do some filtering on the data I have ? 我需要获取返回值来对我拥有的数据进行一些过滤?
function doSomethingWithRows(rows) {
//Mymodule.Items
// How to call data here.
}
UPDATE Based on first answer 更新根据第一个答案
<script>
var Mymodule = angular.module('Mymodule', []);
Mymodule.factory('Items', ['$http', function($http){
var Url = "data/ex.csv";
var Items = $http.get(Url).then(function(response){
return csvParser(response.data);
});
return Items;
}]);
var $injector = angular.injector();
$injector.invoke(['Items', function(Items){ console.log(Items) }]);
</script>
error: 错误:
Uncaught Error: Unknown provider: ItemsProvider <- Items
You can use $injector
: 你可以使用$injector
:
var $injector = angular.injector(["ng", "MyModule"]);
$injector.invoke(['Items', function(Items){
/* do stuff */
console.log(Items); // e.g. print the Items
}]);
$injector
is used to retrieve object instances as defined by some provider (eg your Items
factory). $injector
用于检索某些提供程序(例如,您的Items
工厂)定义的对象实例。
I would extend your factory so you can call a function to get the results. 我会扩展你的工厂,这样你就可以调用一个函数来获得结果。
Mymodule.factory('Items', [
'$http',
function($http){
var Items;
this.loadItems = function loadItems() {
var Url = "data/ex.csv";
$http.get(Url).then(function(response){
Items = csvParser(response.data);
});
}
this.returnItems = function returnItems() {
return Items;
}
}]);
Then in your controller: 然后在你的控制器中:
Mymodule.controller("Controller", [
"Items",
function(Items){
Items.loadItems();
function doSomethingWithRows(rows) {
var items = Items.returnItems();
}
}
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.