Building an array of objects in AngularJS: A comprehensive guide

I am working with several input fields such as "Title," "firstname," "lastname," and "date" in which the data is being stored in an Object. However, I now want to create an array of objects for this data so that each time the submit button is clicked, a new object is pushed into the array.

<!DOCTYPE html>
<html lang="en" ng-app="myApp">

<head>
    <meta charset="UTF-8">
    <title>Angular Basic</title>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.8/angular-material.min.css">
</head>

<body ng-controller="myCtrl">
    <form>
        <md-input-container>
            <label>Title</label>
            <input ng-model="user.title">
        </md-input-container>
        <md-input-container>
            <label>First Name</label>
            <input ng-model="user.first_name">
        </md-input-container>
        <md-input-container>
            <label>Last Name</label>
            <input ng-model="user.last_name">
        </md-input-container>
        <md-input-container>
            <label>Enter date</label>
            <md-datepicker ng-model="user.submissionDate"></md-datepicker>
        </md-input-container>
        <md-button class="md-raised md-warn" ng-click="saveData()">Submit</md-button>
    </form>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-animate.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-aria.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.8/angular-material.min.js"></script>
    <script src="app.js"></script>
</body>

</html>

JS file:

var app = angular.module('myApp', ['ngMaterial']).controller('myCtrl', function ($scope) {
    $scope.user = {}
    var userArr = [];

    $scope.saveData = function () {
        console.log("user", $scope.user)
        userArr.push(user);
        console.log(userArr);
    }
})

Answer №1

You overlooked the inclusion of $scope by the user.

 var module = angular.module('myApp', ['ngMaterial']).controller('myCtrl', 
    function ($scope) {
        $scope.user = {}
        var arrayUser = [];

        $scope.storeData = function () {
            console.log("user", $scope.user)
            arrayUser.push($scope.user)
            console.log(arrayUser);
        }
    })

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

The functionality of this.clusterer is not defined when trying to add a marker using this.clusterer.addMarker(marker);

I'm encountering an error message that says this.clusterer is undefined. Below is an overview of my configuration. Expected behavior: The page should load, then AJAX-load the markers from the controller using the query defined in #search_form. Finall ...

AngularJS: Trouble with ui-sref and state navigation

I've been working on a project and I'm trying to redirect the content to a page in angularjs, but I keep encountering this error: angular.js:12477 Error: Could not resolve 'dashboard.home' from state 'dashboard' This is my c ...

Executing MySQL queries using Ajax

Having trouble with a registration form that relies on jQuery and Ajax for validation. The issue arises when the server-side validation of the e-mail address, among other things, fails to return a result through $msg. function checkUser () { $search = ...

Trouble with CSS full height implementation within a scrolling container

I have been grappling with this straightforward issue for quite some time now. It seems to be a unique problem as I couldn't uncover a similar one online. My goal is to set the height of the green bar to 100% (to match the height of the red parent el ...

Clickable Links in Datatables.js

Currently utilizing DataTables.js and aiming to make each cell in a column clickable as a URL link directing to google.com. I have been facing difficulties getting this functionality to work despite following various tutorials. Below is my current code sn ...

Hide the previous dropdown content in Vue JS by manipulating the visibility of the elements

I'm currently working on creating a Dropdown feature, but I'm facing an issue with hiding the dropdown content when another dropdown is clicked. <template> <div class="dropdown-container"> <div v-for="(it ...

Retrieve the Corresponding Content Inside the Div Element

I have a div with text that needs to be matched with comma-separated values: <div class="val"> This is paragraph 1 </div> <div class="val"> This is paragraph 2 </div> Using an Ajax call, I retrieve the ...

Mastering Protractor for AngularJS testing - Effectively chaining promises for seamless animationswaitForAnimationCompletion

I'm in the process of creating an automated test suite for our company's AngularJS application. I've already developed several test cases that are running smoothly, but I've hit a roadblock with the current test I'm working on invo ...

What are the steps to transform an object containing arrays into strings and then embed them into my HTML code?

Here is the code I need to add to my errors array and send the values to my HTML client-side template: { "email": [ "user with this email already exists." ] } I am looking for something like this: "user with t ...

A sudden change in the behavior of Javascript's .css("font-weight") function

I recently encountered an issue with my Javascript method that checks for bold font-weight on an element. function selected(element) { return element.css("font-weight") === "bold"; } Although the code used to work perfectly fine, it suddenly stopped ...

Why is $watch not working inside tabs in AngularJS?

Check out this example on Plunker Hello everyone, In the provided example, there are two input text boxes created - one outside the tab and another inside. A watch function has been implemented for both of them. However, the watch function for the input ...

What is the best way to transfer data from processing.js to a rails application?

I am working on a basic canvas project using processing.js, and I am wondering how I can transfer data from my Rails application to Processing.js. void drawBox(int bx, int by, int bs, int bs){ strokeWeight(3); stroke(50,50,50); // Test ...

What is the best way to eliminate the additional slash from an optional parameter at the first level in a URL

Is it possible to make the first parameter optional for the login state? Below is the .state definition that I am using: $stateProvider .state("login", { url: '/:team/login/', templateUrl: 'app/user/login.html', ...

"Swapping out a parent view with a child route component in Vue: Step-by-step

I have created Vue routes with a parent route for 'dashboard' and a child route for 'report', set up like this: { path: '/dashboard', component: dashboard, children: [ { path:'report', com ...

Utilizing a function to populate an attribute using .attr() in d3

I utilize .attr to generate link paths in D3, as demonstrated in Lines 42 of the live demo: link.each(function (d){}) .attr('x1', function (d) { return d.source.x; }) .attr('y1', function (d) { return d.source.y; }) .a ...

Guide on how to send users to a personalized 404 page on remix.run

I'm having trouble redirecting the URL to a custom 404 page in remix.run. My URL structure looks like this - app/ ├── routes/ │ ├── $dynamicfolder/ │ │ ├── index.tsx │ │ ├── somepage.tsx │ │ ├ ...

Problem encountered when utilizing map() function - it returns undefined

const items = [ { item: "apple", cost: 2 }, { item: "orange", cost: 4 }, { item: "carrot", cost: "" }, { item: "grapes", cost: 5 }, { item: "milk", cost: 3 }, { item: "bread" ...

Registration of Laravel Vue.js components

I am currently working on a Vue.js application in conjunction with Laravel. To get started, I registered Vue.js like this: import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); import App from './compone ...

Invoking a React function repeatedly (every second)

Currently, I am working with React and utilizing Material UI to create a modal. The modal is rendered as part of the body of the code, placed at the bottom of the page. Its visibility is controlled by the state; if it's open or closed. However, I&apos ...

Switching the visibility of rows in a table

Imagine this as my example table: <table> <tr> <td>a</td> <td>one</td> <td>two</td> </tr> <tr> <td>b</td> <td>three</td> <td>four</t ...