Bill Bill - 4 months ago 12
AngularJS Question

Angular Display lists from Firebase

My data in Firebase looks like this...

evalu8er
situations
-K6rM12D-0nt4fJH_QcA
situation: "Test"
-K6rPoHiUl2N2JOSWXww
situation: "Test2"
-K6rPqbkBHJ-K8znVzay
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">
</div>
<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>
</form>


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("https://evalu8er.firebaseio.com/situations");

ref.push().set({
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("https://evalu8er.firebaseio.com/user/situations/");
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 }}
</li>


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...

{"situation":"Test"}
{"situation":"Test2"}
{"situation":"Test3"}


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

Test
Test2
Test3


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

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 }}
</li>

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 }}
</li>