0

I want to update my DOM element everytime the value on the Firebase changes. I've seen that Angularfire handles three-way data binding, but from what I understood it only works if you take elements from $firebaseArray directly from the DOM.

What I have is an Element on the DOM (chart) that depends on some of the data on a $firebaseArray, but my element gets the data from a function instead of directly from the $firebaseArray. That means I have to do some pre-processing on the $firebaseArray before my element can use it.

This is what I have:

<pie-chart ng-repeat="chart in myCtrl.charts"
           data="chart.data"
           options="chart.options"></pie-chart>

This is my controller:

function MyCtrl($firebaseArray) {
  let myRef = new Firebase(refUrl);
  let chartsFirebase = $firebaseArray(myRef);

  let getCharts = function() {
    let charts = [];
    distanceGoals.$loaded().then(function() {
      // push some things from chartsFirebase on the charts array
      charts.push({
        options: { ... },
        data: [ ... ] 
      }); 
    }
    return charts;
  }

  this.charts = getCharts();
}

Turns out that in this way this.charts is only updated one time, after modifications on the data in Firebase I have to refresh the browser.

  • Has anyone an idea of what I could do to achieve this behavior?
lhahn
  • 1,241
  • 2
  • 14
  • 40
  • As the docs and a couple dozen question I've answered here on Stack Overflow indicate, if you're using $loaded for anything but debugging, you're probably doing it wrong and probably want to use $extend. (I authored the code for $loaded and $extend). – Kato Jan 31 '16 at 17:08

2 Answers2

1

You can add a child-changed event listener to your ref like this:

// Get a reference to our posts
var ref = new Firebase("https://docs-examples.firebaseio.com/web/saving-data/fireblog/posts");
// Get the data on a post that has changed
ref.on("child_changed", function(snapshot) {
  var changedPost = snapshot.val();
  console.log("The updated post title is " + changedPost.title);
});

This will get called everytime something changes in the location you put the listener on. For more info take a look at https://www.firebase.com/docs/web/guide/retrieving-data.html and https://www.firebase.com/docs/web/api/query/on.html.

André Kool
  • 4,880
  • 12
  • 34
  • 44
1

From the AngularFire documentation on $loaded()(emphasis mine):

Returns a promise which is resolved when the initial array data has been downloaded from the database.

That explains the behavior you're seeing.

To solve this, you should extend the $firebaseArray as documented here: https://www.firebase.com/docs/web/libraries/angular/guide/extending-services.html#section-firebasearray

Some related questions:

Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807