Looking to include a new item into an array with the help of AngularJS

Having just started with angularJS, I am facing difficulties in adding an object from a form to an array. When I click on "Add New Product", it triggers the "newItemModal". I enter the new product information but the submit button doesn't seem to work. I want the new product to be added to my items array when I click on submit.

Furthermore, after filling out the new product details under the "newItemModal" modal and then closing the form to open the "editItemModal" using the button under the "Item Number" column, the form displays the same information that was entered in the "Add New Product" form.

HTML CODE

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Bodega Ilusion</title>

    <!-- Bootstrap Core CSS -->
    <link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <!-- MetisMenu CSS -->
    <link href="../vendor/metisMenu/metisMenu.min.css" rel="stylesheet">

    <!-- Custom CSS -->
    <link href="../dist/css/sb-admin-2.css" rel="stylesheet">

    <!-- Morris Charts CSS -->
    <link href="../vendor/morrisjs/morris.css" rel="stylesheet">

    <!-- Custom Fonts -->
    <link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

</head>

<body>

<div id="wrapper">

...

AngularJS CODE

(function(){
var app = angular.module("inventory", []);

app.controller("InventoryController", function($scope){

    $scope.product = {};

    $scope.addProduct = function(product){
        console.log("it worked")
        $scope.product.createdOn = Date.now();
        product.push($scope.product);

    $scope.product = {};
    };

    $scope.items = [
        {
        code:"FD1",
        description: "Happy valentines",
        in: 50,
        out: 20,
        total: 30,
        createdOn: 1397490980837
        },
        {
        code:"FD2",
        description: "Happy Mothers Day",
        in: 70,
        out: 20,
        total: 50,
        createdOn: 1397490980837            
        },
        {
        code:"FD3",
        description: "I Love You",
        in: 100,
        out: 30,
        total: 70,
        createdOn: 1397490980837
        },
        ...

    ];
});


})();

Answer №1

When adding a new product object to the product array, remember to actually push it into your $scope.items array.

Consider this alternative approach:

    $scope.addProduct = function(product){
        console.log("Success!")
        $scope.product.createdOn = Date.now();
        $scope.items.push($scope.product);

    $scope.product = {};
    };

Answer №2

Implement the following modifications and give it a try:

<form name="myForm" novalidate ng-submit="inventoryCtrl.addProduct(item)">

update to

<form name="myForm" novalidate ng-submit="inventoryCtrl.addProduct(inventoryCtrl.item)">

within your controller,

following the line $scope.product = {}; include $scope.item= {};

alter the function addProduct to

$scope.addProduct = function(product){
   console.log("it worked")
   product.createdOn = Date.now();
   $scope.items.push(product);
};

It seems like there is no longer a necessity for $scope.product in the controller.

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

Using Key Press to Rotate Messages - Jquery

Need help with rotating an array based on alphanumeric key presses? Check out the code snippet I've been working on below. Unfortunately, I'm having trouble getting the loop to function properly. Any suggestions or feedback would be greatly appre ...

Extract and preserve elements from an ordered array by segregating them into separate arrays of objects using Angular 8

I have an array called arrayReceived containing 15 objects. My goal is to sort and store the first 6 objects with the lowest amount value in a new array called arraySorted. These objects are sorted based on their amount parameter. There may be multiple obj ...

Issue with Heroku: Unable to serve images through NodeJS Express server

I have an app deployed on Heroku that displays an image. app.js package.json package-lock.json public |__ image1.png |__ image2.png This is the code within app.js const express = require('express'); const app = express(); const path = re ...

Separate a collection of arrays using a set of individual values

Is there a more efficient way to divide each element of an array A by the corresponding scalar in array B, without using list comprehensions? >>> A.shape (4,173,1469) >>> B.shape (4,173) >>> # Improved approach: >>> np. ...

Issue with UseState causing a re-render not to be triggered

My orders list state works perfectly on the initial update. However, when an order in the database gets updated, the order list is updated but fails to trigger a re-render even with <...> const [orders, setOrders] = useState([]); useEffect(( ...

Utilize the Vue-Chartjs plugin registration for a specific chart component only

I am currently working with a chart component in Vue 3 using the composition API. My goal is to incorporate the datalabels plugin into this specific chart only. Upon attempting to register the plugin outside of the chart's data or options, I noticed ...

Using CSS3 translate will result in children becoming relatively positioned

I am facing an issue with a sidebar that contains 2 divs. <div class="sectionsContainer clearfix"><-- Sidebar --> <div class="leftSection pull-left"> <p>Maor</p> </div> <div class="rightSection pu ...

What is the best way to extract multiple values from a JavaScript variable and transfer them to Node.js?

Script JavaScript script snippet embedded at the bottom of an HTML file: var savedValues = [] var currentId = document.getElementById("fridgeFreezer").value function handleChange() { // Logic to handle user input changes: var temp = document.ge ...

What is the best way to pass multiple parameters along with the context to a URL in Vuex?

Link to StackBlitz I am currently working on how to send multiple action parameters with context to a URL. I have been encountering a 400 error in my attempts. The selectedPoint and departurePoint are coming from child components and stored as variables i ...

Integrating Dialogflow with a Heroku JavaScript application

After extensive research, I delved into the realm of integrating DialogFlow requests with a webhook hosted on platforms like Heroku. With both Heroku and nodeJS impeccably installed on my system, I diligently followed the heroku tutorial to kickstart the p ...

Issue: encountered an ECONNRESET error when attempting to read using the request module in mode.js

When attempting to download and parse large XML files from affiliate sites without a proper API, I encounter the same error consistently while using the request module for Node.js. Error: read ECONNRESET at exports._errnoException (util.js:746:11) at TCP. ...

Using axios to pass parameters in a URL with the GET method on a localhost server

I need help using Axios to consume my Go lang API in my React front-end. The route for the API is localhost:1323/profile/email/:email/password/:password, but I'm struggling to figure out how to pass the email and password parameters in the Axios GET r ...

How can you show the default calendar for a specific month and year in a Vue3 datepicker?

I've been utilizing the @vuepic/vue3datepicker component, which automatically shows the days of the current month when integrated in my project: <template> <VueDatePicker v-model="date" inline></VueDatePicker> </templ ...

Creating Stunning CSS Animations for a Slider Using SVG

Looking for help to create an SVG CSS animation for a slider using a mockup image. The animation will feature a balloon with a number value that zooms in and out from left to right or right to left. Currently stuck at the starting point and unsure how to ...

Accessing the value returned by an asynchronous function in Node.js with Electron

As I embark on a new project, my goal is to take user input, process it through a function, and then return the updated value back to the user. Despite being a novice with async functions, I've done extensive research but still can't pinpoint if ...

Generating a JavaScript object from a string to optimize its compatibility with datatables

This inquiry pertains to the plugin available at: var hidecols = '{"sClass": "Hide", "aTargets": [0]},{"sClass": "asdf", "aTargets": [1]},{"sClass": "qwer", "aTargets": [2]}'; var hidecolsobj = eval('(' + hidecols + ')'); ...

The handleClose() function in React is currently writing to the console but failing to close the child element

Currently, I am in the process of creating a small online store for my personal business. Although I have limited experience with React, I believe I have managed to make some progress and might be able to complete something that is at least functional, eve ...

Transmitting a JavaScript file via a Node.js server

I have a NodeJS server that sends a JavaScript file to the client. However, the JavaScript file does not import the libraries it needs on the client side. I load these libraries on the client side before receiving the file. Why is the file unable to find t ...

Customizing the `toString()` method in Node.js exports

I'm having trouble overriding a toString() method in my code. I've already checked here and here, but haven't been able to solve the issue. This is what my code looks like: var Foo = function(arg) { // some code here... return fun ...

Updating a validation directive on $watch in AngularJS version 1.2

I created a directive for validation on a multi-select that allows for dynamic length validation of selected items. The directive is used like this: (function() { 'use strict'; angular .module('myModule') .dire ...