0
votes

This jsfiddle was written as an example from the "Creating AngularFire Services" section in the angularfire docs.

As you can see, the controller is supposed to add a new project using:

.controller('CreateCtrl', function($scope, $location, $timeout, Projects) {
  $scope.save = function() {
    Projects.$add($scope.project, function() {
      $timeout(function() { $location.path('/'); });
    });
  };
})

and if you try to do it, you'll also see that it doesn't work, and the dev console will also show the error "undefined is not a function" pointing to this line:

 Projects.$add($scope.project, function() {

How can this be fixed? Essencially, what I'm asking is: How to add an element to a firebase element, using an AngularFire extended service?

1

1 Answers

1
votes

This isn't a code critique forum, but there are some structural issues I'd like to address first, as they have lead to the issue with $add and feel important to the discussion.

You're synchronizing all of the projects path, but then also have a getById() method that synchronizes the same data again. Instead of using AngularFire's strengths (providing you with a bindings API), this odd semantical structure forces it into a CRUD paradigm and complicates using the synchronized array.

The reason $add does not exists lies in the above. Projects is not a synchronized AngularFire array, but the odd wrapper that you've placed over it, so it makes sense that $add does not exist.

So to stop belaboring my thoughts on why this shouldn't be wrapped in this odd way, and get to the point, you need to extract the array from your wrapper before calling $add:

 Projects.getAll().$add( $scope.project );

One last note, you have attempted to pass a callback function into the $add method. Have a close look at the guide and the API. You'll see that all these methods return promises. So your callback would be moved into .then like so:

 Projects.getAll().$add( $scope.project ).then( /* success function */, /* error function  */ );

One last note on design: The "project" object should probably be fetched with $asObject() instead of $asArray() since it represents a single entity and not a collection.

Hope that helps!