问题描述
我在angular.js应用程序上有一个服务,该服务在其作用域(自身)中创建一个变量(filteredDataGlobal),并具有另一个函数来返回该变量.
I have a service on my angular.js app that creates a variable (filteredDataGlobal) in it's scope (self) and has another function to return that variable.
.service('Utilities',function(){
var self = this;
self.someFunction = function(){
///does calculations then assigns the results in a variable (filteredDataGlobal)
self.filteredDataGlobal = finalResults;
}
self.getFilteredData = function(){
return self.filteredDataGlobal;
};
}
问题是self.someFunction需要花费一些时间(在http请求后进行计算),因此当您在具有Utilities服务的控制器中并尝试像这样访问self.filteredDataGlobal变量时,它将记录为未定义
The problem is self.someFunction takes time to happen (calculations made after an http request) so that when you're in a controller that has the Utilities service and try to access the self.filteredDataGlobal variable like so, it's logged as undefined
.controller('MyController', function(Utilities) {
var self = this;
self.filteredData = Utilities.getFilteredData();
console.log(self.filteredData);
})
在控制器中使用self.filteredDataGlobal之前,我将如何在其实用工具中监视" self.filteredDataGlobal准备就绪?
How would I 'watch' for self.filteredDataGlobal to be ready in the Utilities function before I use it in my controller?
推荐答案
我同意Mridul Kashyap的回答.但我想添加有关第2点的内容,您可以按照以下步骤操作:
I agree with Mridul Kashyap answer. but I want to add something regarding point 2 that you can do as following:
app.controller("MyController", MyController);
function MyController($scope, selectedService){
selectedService.$promise.then(function(data){
$scope.myData = data;
//fill your logic here.
}
}
如果您这样做的话,请确保在兑现承诺后填写$ scope变量
if you do like that, you ensure that you fill your $scope variables when the promise is resolved
这篇关于Angular.js:将变量从实用程序函数获取到控制器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!