Bill Bill - 1 year ago 74
AngularJS Question

Angular Display lists from Firebase

My data in Firebase looks like this...

situation: "Test"
situation: "Test2"
situation: "Test3"

I have inserted the data from an HTML page via a form like this...

<div class="form-group">
<label for="situation">Add a situation</label>
<input type="text" class="form-control" id="situation" placeholder="Situation" ng-model="situation">
<button type="submit" class="btn btn-default pull-right" ng-click="add_situation()"><i class="fa fa-cog fa-spin" ng-show="loading"></i> Add </button>

The above form is calling the controller...

app.controller("situations", ["$scope", function ($scope) {
$scope.add_situation = function () {
var situation = $scope.situation;
var ref = new Firebase("");

situation: situation

Now I want to get each of the situations back to the page, and this where it all goes wrong for me.

Inside the same controller as above I'm adding this....

var ref = new Firebase("");
ref.on("value", function(snapshot) {
$scope.display_situatoins = snapshot.val();
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);

And on the HTML page I have added

<li data-ng-repeat="x in display_situatoins">
{{ x }}

When the page loads it DOES NOT show me the data until I enter something in the form field,

Question 1/3)
How do I get the data to show on page load?

When it does load it looks like this...


And what I want is just to show a list of the situations like this..


Question 2/3)
How do I just show the situation values as above?

And when I do add a new item it gets listed at the bottom, how do I order the list with the new items at the top?

Question 3/3)
How do I order the list so the new items appear first?

Answer Source

Use AngularFire for synchronized collections.

angular.module('app', ['firebase'])
  .constant('FirebaseUrl', '<my-firebase-app>')
  .service('rootRef', ['FirebaseUrl', Firebase])
  .controller('MyCtrl', MyController);

function MyCtrl($scope, rootRef, $firebaseArray) {
   $scope.situations = $firebaseArray(rootRef.child('situations');

Then in your template for MyCtrl, you can do an ng-repeat on the situations array.

<li ng-repeat="situation in situations">
    {{ situation.situation }}

The {{ situation.situation }} part looks awkward because of the naming. If you change the property situation to something like text or title it would look like:

<li ng-repeat="situation in situations">
    {{ situation.title }}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download