Error in AngularJS push() method

I am facing a challenge with an AngularJS application I am currently working on. My background is more in jQuery development, so please bear with me ;)

The issue lies in a factory that retrieves categories through an $http call:

app.factory('simpleFactory', function($http, $routeParams) {
var categories = [];
var factory = {};

factory.getCategories = function() {
    return $http({
        url: '/system/getlist/',
        data: { id : pageID },
        method: "POST",
    })
    .success(function(addData) {
        categories = addData;
    });
}

return factory; });

My controller sets up a scope to fetch the data from the factory:

app.controller('loadCategories', function ($scope, simpleFactory) {
$scope.categories = [];
init();

function init() {
    $scope.categories = simpleFactory.getCategories();
}

});

Now, I have a second scope triggered from my view (createCategory()) to add a new item to my categories. I attempted to push this new item into the existing $scope.categories like so:

$scope.createCategory = function(cat,catName,catLvl,catType) {
    var catName = catName;
    var parentID = cat.id;

    $http({
        url: '/system/createcategory/',
        data: { catName : catName, parentID : parentID, pageID: pageID, catLvl: catLvl, catType: catType },
        method: "POST",
    })
    .success(function(addData) {
        $scope.categories.push(addData); 

    }); 
}

This additional controller also resides within the loadCategories controller.

THE ISSUE:

Upon trying to push() something into my $scope.categories, I encounter the following error:

TypeError: Object # has no method 'push'

Any insights on why this error occurs? Am I implementing something incorrectly?

The ajax call completes and the success callback is triggered, but there seems to be an issue with the push().

As I am still learning AngularJS, your patience is greatly appreciated :)

Answer №1

simpleFactory.retrieveCategories = function() {
    return $scope.categories = simpleFactory.getCategories();
}

The promise object is being returned, not an array. Since promise objects do not have a method push(), it is recommended to modify the getCategories() method to return an array.

Answer №2

Ph0en1x's solution is spot on - ensure the promise is allowed to run before assigning the scope variable, like so:

simpleFactory.fetchCategories().then(function(data) {
  $scope.categories = data;
});

Additionally, I would recommend modifying the simpleFactory to also return the categories for easier assignment.

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

Filtering with AngularJS based on an array of IDs

span class="list-group-item" ng-click="filterByCtg = {ctgid:'12'}">category div ng-repeat="product in products | filter:search | filter:filterByCtg |orderBy:orderByFilter:reverse"> I need to assign an array of IDs to the filterByCtg for ...

Implementing dynamic loading of a view partial with CodeIgniter and jQuery

I am currently developing a single page application using CodeIgniter and jQuery. The master page consists of the upper part of HTML including the CSS. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8> <met ...

Understanding which specific column is undergoing modification

I've been struggling to find a solution that tells me which specific column is being updated in handsontable. I know they use a textarea for input and then populate the table with values, but I can't seem to figure out how to identify the exact c ...

The collision function is currently not functioning properly, causing a hindrance in movement. There are no other codes restricting movement

const rightPressed = false; const leftPressed = false; const upPressed = false; const downPressed = false; const players = []; players[0] = new victim(1234); const arrayw = 50; const arrayh = 50; const canvas = document.getElementById("myCanvas"); const ...

Having trouble retrieving data from Redux in React

I'm struggling to load data from my state into a form. After logging in and saving the email and token into Redux state, I encounter an issue when trying to display the email within the form on a test page. Despite being able to see the email on TestP ...

Building Dynamic Columns within a react.js Environment

Can anyone help me with creating a dynamic column in react.js? I've already managed to do it with static columns, but now I want to make them dynamic. Take a look at my code below and please provide suggestions. import React from 'react'; i ...

Component not refreshing when state changes occur

I have a unique react application that resembles the one showcased in this codesandbox link https://codesandbox.io/s/eatery-v1691 By clicking on the Menu located at the bottom center of the page, it triggers the display of the MenuFilter component. The M ...

How can you display a set of components in React using TypeScript?

I'm currently working on rendering an array of JSX Components. I've identified two possible methods to achieve this. Method one (current approach): Create the array as an object type that stores the component properties and then build the JSX co ...

Understanding the process of sending data from a Cordova application to a PHP script and storing it in

I'm a beginner in cordova app development and I have a question about posting data from a form in a cordova application using PHP and MongoDB. I have my index.html file in the cordova app and comment.php in c:/xampp/htdocs. I want to display data from ...

Dynamically loading components within an Angular application

I am tasked with displaying different components at specific times by iterating through them. Below is an example of how I have attempted to achieve this. The components I can use are determined by the server. <ngb-tabset [activeId]="1"> ...

How can I update the input field status once the form submission validation has been completed?

Is there a way to manually change the validity status of an input field using JavaScript? I have an input field used for searching, and after receiving a response from the server, I need to mark if the input value is correct or incorrect. Currently, I can ...

Enhance your content using Bootstrap modal and AngularJS

I have created a bootstrap modal for editing specific data from my data table. I am able to open the popup and fetch the data successfully, but when I make changes in the modal's text box, it immediately reflects in the data table as well (which is lo ...

The disabled functionality of AddCircleIcon in Material UI seems to be malfunctioning

The AddCircleIcon button's disabled functionality is not working, even though the onClick function is functioning properly. Even when directly passing true to the disabled property, it still doesn't work. I am in need of assistance to resolve thi ...

Building a Many-to-Many Relationship in Node.js Using Sequelize.js

As I utilize the sequelize node.js module to structure schema in Postgres SQL, I have defined two schemas for Project and my users. Project Schema module.exports = function(sequelize, DataTypes) { var project = sequelize.define('project', { ...

Utilizing foreign keys to insert data into a database within a React application

Utilizing React, I am sending data to my PostgreSQL database through NodeJS. Within my songs and image tables, there is a foreign key (id) that references the album id for title, date, and description. The album table utilizes a uuid for its id. My query p ...

The Javascript style.opacity function eliminates the leading zero from the input string

In my application, users have the ability to change the color of the background but not the pattern. They can adjust the background behind the pattern and the opacity of the pattern. Users are prompted to input a percentage, which is actually a number betw ...

Tips for transferring an id through pagination buttons without altering the link on a single PHP page

Is there a way to pass a value in PHP without refreshing the page or changing the link? $pagination .= '<li class="page-item"><a class="page-link" href="/demo-project/book?page='.$i.'">'.$i.'</a></li>' ...

Using Typescript with Protractor for Dropdown Menus

As a newcomer to Protractor, I am looking to automate the selection of a dropdown. While I have some knowledge in JavaScript, I am currently working with typescript. Can someone advise me on how to select the dropdown option based on the text provided? Fo ...

What could be causing Node to encounter difficulties in locating the SubmitEvent?

I'm currently integrating unit tests with jest into my React app. The code snippet I have in my test is giving me trouble, as it throws a "ReferenceError: SubmitEvent is not defined" when executed. taskInputForm.dispatchEvent(new SubmitEvent("submit" ...

Retrieve a collection of items from an s3 bucket (either min.io or Amazon) by utilizing a promise

I am attempting to retrieve a list of object names from an s3 bucket using the Min.io JavaScript API (). When I make the API call, it returns a stream, but unfortunately, I always end up with an empty list. An example of the dataStream looks like this: { ...