angularFire encounters difficulties when attempting to add information to Firebase

I am currently utilizing angularFire and attempting to save form data to firebase using $add. Any assistance on this matter would be highly appreciated. All the console logs are showing correctly, as I am able to view the data in the console. Apologies for the extensive code provided... I wanted to ensure that all necessary information was included.

app.js:

    var creativeBillingApp = angular.module('creativeBillingApp', ['ngRoute', 'firebase']);

    creativeBillingApp.constant('FIREBASE_URI', "https://XXXX.firebaseIO.com/");

    creativeBillingApp.controller('MainCtrl', ['$scope', 'groupsService', function( $scope,  groupsService, $firebase ) {

    console.log('Works')


    $scope.newGroup = {
     name: '',
     status: ''

    };

   $scope.addGroup = function(newGroup){

   console.log(newGroup);

groupsService.addGroup();
  $scope.newGroup = {
    name: '',
    status: ''

  };
};
 $scope.updateGroup = function (id) {
   groupsService.updateGroup(id);
 };

 $scope.removeGroup = function(id) {
   groupsService.removeGroup(id);
 };
}]);




creativeBillingApp.factory('groupsService', ['$firebase', 'FIREBASE_URI',
  function ($firebase, FIREBASE_URI) {
    'use strict';
    var ref = new Firebase(FIREBASE_URI);
    return $firebase(ref).$asArray();

var groups = $firebase(ref).$asArray();

var getGroups = function(){
  return groups;
};

var addGroup = function (newGroup) {
  console.log(newGroup)
  groups.$add(newGroup);
};

var updateGroup = function (id){
  groups.$save(id);
};

var removeGroup = function (id) {
  groups.$remove(id);
};
return {
  getGroups: getGroups,
  addGroup: addGroup,
  updateGroup: updateGroup,
  removeGroup: removeGroup,
}

}]);

index.html:

         <form role="form" ng-submit="addGroup(newGroup)">
            <div class="form-group">
              <label for="groupName">Group Name</label>
              <input type="text" class="form-control" id="groupName" ng-model="newGroup.name">
            </div>
            <div class="form-group">
              <label for="groupStatus">Group Status</label>
              <select class="form-control" ng-model="newGroup.status">
                <option value="inactive">Inactive</option>
                <option value="active">Active</option>
              </select>
            </div>
           <button type="submit" class="btn btn-default">Submit</button>
          </form>

An error message is appearing:

TypeError: undefined is not a function
at Scope.$scope.addGroup (http://localhost:9000/scripts/app.js:35:19)

The issue seems to stem from line 35 in app.js, specifically related to calling groupsService.addGroup(); based on the above code snippet.

Answer №1

Initially, after creating your $FirebaseArray, you are returning in your service and then creating another $FirebaseArray.

return $firebase(ref).$asArray();

Please remove that return statement as it is causing your service to terminate prematurely, resulting in none of the attached methods being applied to your service.

In the function groupService.addGroup(), you are using push, which is not a valid function for $asArray. Instead, you should use .$add(). Also, ensure that the newGroup argument is properly passed into the controller.

The method $push is accessible from the base of the $firebase binding. When utilizing a $FirebaseArray, the $add method is used to push a new record into Firebase.

Refer to the documentation for further details.

View Plunker Demo

var addGroup = function (newGroup) {
  console.log(newGroup)
  groups.$add(newGroup);
};

Subsequently, in your controller, you can easily execute:

$scope.addGroup = function(newGroup){
  groupsService.addGroup(newGroup);

  $scope.newGroup = {
    name: '',
    status: ''
  };
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating an Object with Quoted Key in JavaScript/Typescript for MongoDB's '$push' Feature

Struggling to format the data in order to add an element into a nested array within MongoDB. Currently attempting this in TypeScript: var data = {$push:{"foo.12.bar":{ prop1: prop1, prop2: prop2, // referenced values above this code snippet ...

Implementing a JavaScript function to trigger the 'GET' method upon page load repeatedly

I am facing a strange issue where a javascript function is running multiple times upon page load (7 times in Chrome, 3 times in IE, 7 times in Firefox, 6 times in Opera, 4 times in Safari, and 4 times in Edge). What's going on??? Moreover, the xmlHtt ...

Customizing error styles in a table using Jquery validation

My form is using JQuery .validation(). Here is the structure of my form: <form....> <table cellspacing="0" cellpadding="0"> <tr> <td>Name: </td> <td><input type='text' name='Name'/></td> ...

React - dynamically injecting external logic during execution

My goal is to modularize my React application by loading additional logic (such as containers/components) dynamically from an external .js file during runtime. For instance, I want to be able to introduce a new tab with completely different functionality o ...

Dispose the inputpicker filter after setting the value

I am currently utilizing the "Jquery inputpicker plugin" for creating dropdown menus. More information about this plugin can be found here. To initialize my dropdown, I use the following code: $('#test').inputpicker({ data:[ {value:"1 ...

I have a specific resolution in mind where I want to run jQuery code during window scrolling

I have a jQuery code that I want to run only when the resolution is greater than 950px. If not, I risk losing the responsive logo. My goal is to create a navigation bar similar to the one on the Lenovo homepage. $(document).ready(function(){ //left ...

Is there a way to execute a callback function once the page has finished loading through AJAX in

I'm in need of a way to attach new events and execute certain functions on a webpage that loads dynamically. Unfortunately, the resources I've found so far are outdated or lack necessary details (even the jqm docs). My current setup involves jQue ...

Ensure that the Bootstrap form validation checks for both an empty field and a valid URL

I'm currently working on validating a form field in Bootstrap 4.4. The goal is to not only check if the field is filled out, but also to ensure that it contains a valid URL. This URL can be an internal link, a hostname, or an IP address. However, it m ...

Is there a way to track and observe the vertical movement of an element within a directive's link function?

Can you help me figure out the best way to $watch or bind the height position of an element? I have a scenario where I display three divs, one at a time in different tabs (using bootstrap). Each div has a different height, and my directive comes after thes ...

"Implement a smooth scrolling animation on the page to automatically move a div element upward and lock

I am attempting to create a unique animation for a header div that involves moving it to the top of the screen when the user scrolls down. Once the header div reaches the top, I want it to stay fixed in that position. As the header div moves upwards, it wi ...

What could be the reason for an async function to send an empty object in the request body?

I'm currently utilizing nuxt.js, mongoDB, express, and bodyParser as well Unfortunately, the solutions provided by others do not solve my issue, as having bodyParser does not seem to fix it. The uploadPet function is designed to collect form data an ...

Tips for passing multiple parameters to Web API controller methods in Angular 4

Want to learn how to use Spring Rest Api: @RequestMapping(value={"/save-userlist"}, method=RequestMethod.POST) public ResponseEntity<?> saveUserList(@RequestBody UserListDTO userListDTO, @RequestBody List<User> users, @RequestParam Integer ...

Navigate to the Bootstrap Panel body when the relevant link is clicked

I am facing an issue with a long list of panels that are tedious to scroll through. To make navigation easier, I am attempting to create a shortcut link at the top of the page. Below is the code for the shortcut: <a data-toggle="collapse" data-parent ...

Is it possible to use CSS to create a gap between the cursor and the placeholder text within an input field?

Could you please assist me with a bug I have encountered on an older version of Firefox for OSX (37.0.2)? I have included a screenshot of the issue here: https://i.sstatic.net/dzK0G.png Is there a way to use css to move the first character of the placehol ...

Creating a Singular Instance for Dynamically Loaded Module in Next.js

I'm currently working on creating a Singleton instance for a dynamically imported module in my Next.js app. However, the problem is that each time I call getInstance, it initializes a new instance instead of reusing the existing one. The following co ...

What are some strategies for incorporating error handling into promise chains and design considerations for working with promises?

As I delve deeper into using promises, the implementation process has left me with uncertainties. Let's say we have a signup function that takes an email address, username, and password, and executes various asynchronous operations in sequence: Che ...

Texturing a sphere using Three.js is not compatible with smartphones

I've encountered some difficulties using Three.js. My goal is to add a texture to a sphere (an image). The code I have works flawlessly... until I attempt to run it on a smartphone. I attempted to debug the issue with Firefox and its remote debugger, ...

What is the best way to transfer attributes from a stateful component to an event handler within a Higher Order Component that encloses a child component?

My current project involves using a framework that requires passing an event handler into a Higher Order Component (HOC) which wraps one of the children of my stateful Page component. <Page> <HOC onClick={fn}> <PageColumn> ...

Showing Variables in JavaScript

<!DOCTYPE HTML> <html> <body> <button onclick="question++">Increment</button> <script> function test() { var question = 0; } </script> </body> </html> Qu ...

How come the filter function produces different results compared to using push with a for..of loop?

After extracting an array of objects from the raw data provided in this link, I have encountered a dataset that resembles the following: [0 ... 99] 0 : city : "New York" growth_from_2000_to_2013 : "4.8%" latitude : 40.7127837 longitude : -74.0059413 popul ...