A.New A.New - 3 months ago 20
AngularJS Question

AngularJS Firebase $add is not a function

I try to push a new record to my Firebase. But everytime I receive a console error like this:

$scope.contacts.$add is not a function


Here is my code:

app.controller('contactsCtrl',['$scope','$firebaseObject',function($scope,$firebaseObject){

var ref = new Firebase("https://<database_details>.firebaseio.com/contacts");

$scope.contacts = $firebaseObject(ref)

$scope.addContact = function(){

$scope.contacts.$add({
name: $scope.name,
address: $scope.address,
telephone: $scope.telephone,
company: $scope.company,
email: $scope.email
}).then(function(ref){

var id = ref.key();
console.log('contact added with Id: ' + id);


});

};
}]);

Answer

You should use $firebaseArray instead of $firebaseObject

app.controller('contactsCtrl','$scope','$firebaseArray',function($scope,$firebaseArray){
 var ref = new Firebase("https://<database_details>.firebaseio.com/contacts");
 $scope.contacts = $firebaseArray(ref)
 $scope.addContact = function(){
     $scope.contacts.$add({
        name: $scope.name,
        address: $scope.address,
        telephone: $scope.telephone,
        company: $scope.company,
        email: $scope.email
        }).then(function(ref){
        var id = ref.key();
        console.log('contact added with Id: ' + id);
    });
   }; 
  }]);