Pushing and getting data from Firebase in AngularJS Factories

JohnAndrews picture JohnAndrews · Dec 3, 2014 · Viewed 8.9k times · Source

I am trying to store and retrieve my data on firebase using AngularJS. I have built so far an Ionic tabs project and created a custom controller and custom factory. I understand that it is a convention to retrieve the data in a factory and handle it through the controllers. However, I don't understand why my following code does not work:

services.js

angular.module('starter.services', ['firebase'])

.factory('OtherFriends', ['$firebase', function ($firebase) {

  var ref = new Firebase("https://example1234.firebaseio.com/friendlist");
  var sync = $firebase(ref);

  var otherfriends = sync.$asArray();

  return {
    all: function() {
      return otherfriends;
    },
    get: function(friendId) {
      // Simple index lookup
      return otherfriends[friendId];
    }
  }
}])

controllers.js

angular.module('starter.controllers', [])

// OTHER CONTROLLERS

.controller('OtherFriendsCtrl', function($scope, OtherFriends) {
  $scope.otherfriends = OtherFriends.all();
})

tab-otherfriends.html

<ion-view title="OtherFriends">
  <ion-content>
    <ion-list>
      <ion-item ng-repeat="otherfriend in otherfriends" type="item-text-wrap" href="#/tab/otherfriend/{{otherfriend.id}}">
        {{otherfriend.name}}
      </ion-item>
    </ion-list>
  </ion-content>
</ion-view>

app.js

angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'firebase'])

// OTHER STANDARD IONIC CODE

.config(function($stateProvider, $urlRouterProvider) {

  // Ionic uses AngularUI Router which uses the concept of states
  // Learn more here: https://github.com/angular-ui/ui-router
  // Set up the various states which the app can be in.
  // Each state's controller can be found in controllers.js
  $stateProvider

    // setup an abstract state for the tabs directive
    .state('tab', {
      url: "/tab",
      abstract: true,
      templateUrl: "templates/tabs.html"
    })

    .state('tab.otherfriends', {
      url: '/otherfriends',
      views: {
        'tab-otherfriends': {
          templateUrl: 'templates/tab-otherfriends.html',
          controller: 'OtherFriendsCtrl'
        }
      }
    })

  // OTHER TABS

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/tab/dash');

});

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->


    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

    <!-- firebase (loaded after ionic bundle) -->
    <script src="https://cdn.firebase.com/js/client/1.0.17/firebase.js"></script>
    <script src="https://cdn.firebase.com/js/simple-login/1.6.2/firebase-simple-login.js"></script>
    <script src="https://cdn.firebase.com/libs/angularfire/0.7.1/angularfire.js"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>
    <script src="js/controllers.js"></script>
    <script src="js/services.js"></script>
  </head>
  <body ng-app="starter" animation="slide-left-right-ios7">
    <!-- 
      The nav bar that will be updated as we navigate between views.
    -->
    <ion-nav-bar class="bar-stable nav-title-slide-ios7">
      <ion-nav-back-button class="button-icon icon  ion-ios7-arrow-back">
        Back
      </ion-nav-back-button>
    </ion-nav-bar>
    <!-- 
      The views will be rendered in the <ion-nav-view> directive below
      Templates are in the /templates folder (but you could also
      have templates inline in this html file if you'd like).
    -->
    <ion-nav-view></ion-nav-view>


  </body>
</html>

And the data in Firebase.io (imported .JSON file):

{"friendlist":[
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

Answer

Saidh picture Saidh · Dec 3, 2014

I think you are facing some asynchronous data loading issue. I am not sure about the $firebase, but u just try

angular.module('starter.services', ['firebase'])

.factory('OtherFriends', ['$firebase', function ($firebase) {

  var ref = new Firebase("https://example1234.firebaseio.com/");
  var sync = $firebase(ref);

  return {
    all: function() {
      return sync.$asArray();
    },
    get: function(friendId) {
      // Simple index lookup
      return otherfriends[friendId];
    }
  }
}])

OR

angular.module('starter.services', ['firebase'])

    .factory('OtherFriends', ['$firebase', function ($firebase) {

      var ref = new Firebase("https://example1234.firebaseio.com/");

      return {
        all: function() {
          return $firebase(ref).$asArray();
        },
        get: function(friendId) {
          // Simple index lookup
          return otherfriends[friendId];
        }
      }
    }])