2

I wonder how to structure the actual push and update methods within a Angular controller when storing to Firebase. For now I think there is lots of duplicated code and bad structure. It looks something like this:

app.controller( "myController", [ "$scope", "$routeParams", function( $scope, $routeParams ) {
    $scope.id = $routeParams.id;
    $scope.save = function() {
        if( $scope.id ) {
            // Update
        }
        else {
            // Save
        }
    }
} ] );

The only difference between update and save is the methods used to store data with Firebase (push/update). Otherwise the object stored is pretty much the same and the callback is handled the same way. This gives a lot of duplicated code. How would I structure this in a good way to prevent duplicated code?

2 Answers 2

7

Use AngularFire.

AngularFire is the officially supported Firebase bindings for AngularJS. It has services to help with synchronized collections and authentication.

What AngularFire can really help you with here is injecting a synchronized collection to a controller via the resolve object in the router.

angular.module('app', ['firebase', 'ngRoute'])
  .config(ApplicationConfig)
  .constant('FirebaseUrl', '<my-firebase-app')
  .service('rootRef', ['FirebaseUrl', Firebase])
  .factory('itemFactory', ItemFactory)
  .controller('MyCtrl', MyCtrl);

function ApplicationConfig($routerProvider) {
  $routeProvider.when('/', {
    templateUrl: 'book.html',
    controller: 'BookController',
    resolve: {
      item: function(itemFactory, $routeParams) {
         // return a promise
         // the resolved data is injected into the controller
         return itemFactory($routeParams.id).$loaded();
      }
    }
  });
}

function ItemFactory(rootRef, $firebaseObject) {
   function ItemFactory(id) {
     var itemRef = rootRef.child('list').child(id);
     return $firebaseObject(itemRef);
   }
}

function MyCtrl($scope, item) {
   $scope.item = item;

   // now you can modify $scope.item and then call $scope.$save()
   // no need to worry whether it's an update or save, no worrying
   // about callbacks or other async data flow      
}
Sign up to request clarification or add additional context in comments.

Comments

3

Maybe like this

//EDIT answer edited according to your comment

app.controller( "myController", [ "$scope", "$routeParams", function( $scope, $routeParams ) {
    $scope.id = $routeParams.id;
    $scope.save = function() {

        //  https://www.firebase.com/docs/web/api/firebase/update.html
        // message when the data has finished synchronizing.
        var onComplete = function(error) {
          if (error) {
            console.log('Synchronization failed');
          } else {
            console.log('Synchronization succeeded');
          }
        };



        var fb = new Firebase( "URL" ); 
        if( $scope.id ) {
            // Update
            fb.update( { DATA }, onComplete  ); 
        }else{
            fb.push( { DATA }, onComplete  ); 
        }


    }
} ] );

4 Comments

Thanks for input but this doesn't have much to do with Firebase though. This is how to store data in Firebase: var fb = new Firebase( "URL" ); fb.push( { DATA }, function() { // Callback } ); or fb.update( { DATA }, function() { // Callback } ); I'm thinking of using the strategy pattern for this. Any suggestions?
I edit my answer, look at the firebug doc for callback function example
Seem like a valid answer. I thought of moving this to a factory and let it handle it: StorageFactory( "URL" ).save( { DATA }, function() { // callback } ); That might work.
There's really no need to use the onComplete callback. Local firebase updates fire first, which give it a snappy feel and the server callback happens later. So if you listen to the callback it may end up being slower. Also you should look into using AngularFire to simplify your controller code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.