Clark McCauley Clark McCauley -4 years ago 74
Javascript Question

AngularJS + Firebase - Scope not updating when getting remote data

I've been working on the problem for about a week now with no progress. I have an array of data that's available to my

$scope
. I iterate through it like this:

<div ng-repeat="device in myData">
<label>{{processor(device.$id)}}</label>
</div>


The data contains only a Firebase
$uid
. And I want to make a second request to the database to get information thats associated with this
$uid
and place it as the label's content. I thought I could use an angular expression with a function to pass in the Firebase
$uid
and return some data.

I declare this
$scope
function:

$scope.processor = function(uid) {
function getDeviceInfo(callback) {
_.child('device/' + uid).once('value', function(snapshot) {
callback(snapshot.val())
})
}
getDeviceInfo(function(data) {
console.log(data)
return data
})
}


Basically I call the
processor($id)
in my scope, passing in the
uid
I want to lookup. The function
getDeviceInfo()
runs and has a callback, when the data is returned, I log it to the console, which works perfect, all the data is there. But then when I try and return a value to the
$scope
, it doesn't update.

I've tried about every combination of Angular/AngularFire code available and haven't gotten anything to work, any ideas?

Answer Source

If the function that you pass as a parameter to the once function is executed asynchronous, you can't return the data from the processor function.

The best you can do is to add the resulting data to the device object or to create another object to hold all the data for all the devices.

Try this:

<div ng-repeat="device in myData">
    <label>{{device.data}}</label>
</div> 

$scope.processor = function(device) {
   _.child('device/' + device.$id).once('value', function(snapshot) {
           device.data = snapshot.val();
     });
   }
}
$scope.myData.forEach($scope.processor);

Or this:

<div ng-repeat="device in myData">
    <label>{{deviceData[device.$id]}}</label>
</div> 

$scope.deviceData = {};
$scope.processor = function(device) {
   _.child('device/' + device.$id).once('value', function(snapshot) {
           $scope.deviceData[device.$id] = snapshot.val();
     });
   }
}
$scope.myData.forEach($scope.processor);

If that function is not asynch you can return the data using something like this:

$scope.processor = function(uid) {
    var data = undefined;
    _.child('device/' + uid).once('value', function(snapshot) {
        data = snapshot.val()
    })
    return data
}

reference

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download