Tyler Brown
Tyler Brown

Reputation: 157

Creating and adding to arrays in angularFire / Firebase

I am trying to build an app with angularjs and Firebase similar to a forum for helping my classmates with problems. I also want people to be able to 'reply' to the specific problems the classmates are having, so I create an object with many values in the angularjs factory, like this:

factory.addError = function() {
 factory.errors.$add({
  ...
  replies: []
 });
};

The problem with this is that Firebase doesn't save parameters with empty values for placeholders, such as the parameter 'replies' above. I have tried to hard code a placeholder value into the array, but that seems like a very patchy solution, and that comes with it's own set of problems for me having to delete out the data in Firebase. For reference, here is the code in the linked controller:

$scope.error.replies.$push({
  name: $scope.replyName,
  message: $scope.replyMessage,
  time: (new Date()).toString(),
  upvote: 0
});

How do you initialize an empty array into the object? And will $push properly use Firebase's commands to save it to it's own set of data?

Upvotes: 2

Views: 3423

Answers (1)

sbolel
sbolel

Reputation: 3526

First, here are some relevant resources and suggestions:

Resources

Suggestions

As the AngularFire API Documentation says:

"There are several powerful techniques for transforming the data downloaded and saved by $firebaseArray and $firebaseObject. These techniques should only be attempted by advanced Angular users who know their way around the code."

Putting all that together, you accomplish what you want to do by:

Example

Extended Error $firebaseObject

.factory('Error', function(fbUrl, ErrorFactory) {
  return function(errorKey){
    var errorRef;
    if(errorKey){
      // Get/set Error by key
      errorRef = new Firebase(fbUrl + '/errors/'+errorKey);
    } else {
      // Create a new Error
      var errorsListRef = new Firebase(fbUrl + '/errors');
      errorRef = errorsListRef.push();
    }
    return new ErrorFactory(errorRef);
  }
})

.factory('ErrorFactory', function($firebaseObject){
  return $firebaseObject.$extend({
    sendReply: function(replyObject) {
      if(replyObject.message.isNotEmpty()) {
        this.$ref().child('replies').push(replyObject);
      } else {
        alert("You need to enter a message.");
      }
    }
  });
})

Error Controller

.controller('ErrorController',function($scope, Error) {
  // Set empty reply message
  $scope.replyMessage = '';

  // Create a new Error $firebaseObject
  var error = new Error();
  $scope.error = error;

  // Send reply to error
  $scope.reply = function(){
      error.sendReply({message:$scope.replyMessage});
  }
})

And String.prototype.isNotEmpty()

String.prototype.isNotEmpty = function() {
    return (this.length !== 0 && this.trim());
};

(adapted from this answer)


Hope that helps!

Upvotes: 3

Related Questions