0

So I want to get a value from function, which uses Firebase. After it, I want to use this value in a view.

My Angular function:

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

My FB looks like:

apple
|_160

And HTML:

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

But in view there is only Apple:

Sergey Pavlov
  • 147
  • 1
  • 11
  • It is going to be populated from the remote server. This is an asynchronous call, so it will take some time before the data becomes available in the controller. While it might be tempting to put a console.log on the next line to read the results, the data won't be downloaded yet, so the object will appear to be empty. – Sajal Jun 21 '15 at 11:08
  • http://stackoverflow.com/questions/27582403/how-to-access-scope-from-async-callback – Numyx Jun 21 '15 at 11:19
  • @qantas-94-heavy I think you're right, sorry for duplicate. But I still can't understand how to make it work in my case. – Sergey Pavlov Jun 21 '15 at 11:46
  • Move the `console.log` statement **into** the callback function to make it work: `indexRef.on("value", function(Index){ console.log(Index.val()); })`. One thing that is helpful to keep in mind for this is that the `value` event will fire any time the value changes, so your console.log will execute every time now. – Frank van Puffelen Jun 21 '15 at 15:47

1 Answers1

1

You need to add $apply to your async callback. Doc link.

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).

Also, using ngInit outside of ngRepeat is considered a bad practice, initialize scope vars in the controller.

(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');
sbedulin
  • 4,102
  • 24
  • 34