2015-06-21 61 views
0

所以我想从使用Firebase的函数获取值。之后,我想在视图中使用这个值。从异步函数返回值时遇到问题

我的角度功能:

$scope.getCurrentIndex = function(companyName){ 
     var indexRef = new Firebase('https://xxxxx-stock.firebaseio.com/'+companyName); 
     indexRef.on("value", function(Index){ 
      return Index.val() 
     }) 
    }; 

我的FB是这样的:

apple 
|_160 

和HTML:

<div ng-init="Index = getCurrentIndex('apple')"> 
    <h2>Apple: {{Index}}</h2> 
</div> 

但鉴于只有Apple:

+0

它将从远程服务器填充。这是一个异步调用,因此在控制器中的数据可用之前需要一些时间。尽管在下一行放置console.log以读取结果可能很诱人,但数据将不会被下载,因此该对象将显示为空。 – Sajal

+0

http://stackoverflow.com/questions/27582403/how-to-access-scope-from-async-callback – Numyx

+0

@ qantas-94-heavy我认为你是对的,抱歉重复。但我仍然无法理解如何使它适用于我的情况。 –

回答

1

你的东东d将$apply添加到您的异步回调。 Doc link.

$ apply()用于从角度框架的外部执行角度表达式。 (例如,来自浏览器DOM事件,setTimeout,XHR或第三方库)。

此外,使用ngInit外ngRepeat被认为a bad practice,初始化范围在控制器瓦尔。

(function getCurrentIndex(companyName) { 
    var indexRef = new Firebase('https://xxxxx-stock.firebaseio.com/' + companyName); 
    indexRef.on("value", function(Index){ 
     $scope.Index = Index.val(); 
     $scope.$apply(); 
    }); 
})('Apple');