Save information gathered from AngularJS input form

I am looking to save and display comment data in the view and store it in a database.

Below is the form I have:


<form>
    <div class="form-group">
        <label>Add a comment</label>
        <input type="text" ng-model="newRole.newAuthor" placeholder="author">
        <input type="date" ng-model="newRole.newDate">
        <input type="file" ng-model="newRole.commentImage">
        <textarea class="form-control metro" ng-model="newRole.newComment"></textarea>
        <h2>{{txtcomment}}</h2> 
    </div>
</form>
<button class="btn btn-primary" ng-click="trip.makeComment(newRole)">Comment</button>

I want to store the data at this location:

this.tripObject.comments = [
{
    "author": "Ronnie Oliver",
    "date": "05/06/16 01:19 PM",
    "imageURL": "/assets/images/placeholders/user.svg",
    "text": "Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Nullam id dolor id nibh ultricies vehicula ut id elit. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Nullam quis risus eget urna mollis ornare vel eu leo. Curabitur blandit tempus porttitor."
},
{
    "author": "Shaggy Rogers",
    "date": "05/06/16 12:48 PM",
    "imageURL": "/assets/images/placeholders/user.svg",
    "text": "Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Nullam id dolor id nibh ultricies vehicula ut id elit. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Nullam quis risus eget urna mollis ornare vel eu leo. Curabitur blandit tempus porttitor."
}
];

This is how the controller looks like:

this.makeComment = function(newRole){
            // $scope.txtcomment = '';
            var newRole = {
                "author":newRole.newAuthor,
                "date":$scope.newDate,
                "imageURL":$scope.commentImage,
                "text" : $scope.newComment
             }
            console.log($scope.newRole);

            console.log($scope.tripObject.comentario)

            this.tripObject.comments.push($scope.newRole);
            console.log(this.tripObject.comments);
        };

I suspect there might be an issue with either the controller or the form, but I'm not sure exactly where.

Answer №1

Begin by initializing

$scope.tripObject={comments:[]};

Next, initialize

$scope.newRole={};

Then, when clicking on makeComment in the JavaScript file

$scope.tripObject.comments.push($scope.newRole);

In this case, newRole represents your object that will be added to the comments list

Answer №2

Instead of using $scope.newDate, you should be using $scope.newRole.newDate. When passing newRole as an argument, you can simplify the code like this:

this.tripObject.comments.push({
  author: newRole.newAuthor,
  date: newRole.newDate,
  imageURL: newRole.commentImage,
  text: newRole.newComment
})

(Also, it's not recommended to reassign newRole to a new variable with the same name).

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

Efficiently adapting html content for Vue localization

I've been utilizing the v-html tag to display HTML in my Vue pages. However, I came across a string that was a complete HTML file with content like this: <html xmlns="https://www.w3.org/1999/xhtml"> <head> .... <style> < ...

Issues with form validators failing to work properly in Angular 2

I'm currently working on an Angular 2 form that utilizes form validators using the form builder module. After entering data in a text box, it successfully passes validation (indicated by a green outline around the div). However, upon loading the for ...

A guide to parsing nested JSON with AngularJS

I am currently working on parsing a nested JSON using AngularJS. Here is an example of the nested JSON structure: { "results": [ { "id": "D1", "name": "A", }, { "id": "D2", "name": "B", } ] } Below is the Angul ...

Error occurred due to an abrupt termination of JSON input while transferring data through ajax communication

<script> $.ajax({ type: "POST", url: "http://localhost:3000/xot/us/confirm", crossDomain: true, dataType : 'json', contentType: "application/json; charset=utf-8", data:JSON.stringify({ username:"User" ...

A guide on unpacking an object and transferring it to a response model

I am dealing with a JSON string that needs to be deserialized in the following way. using (var streamReader = new StreamReader(httpResponsePayment.GetResponseStream())) { var data = streamReader.ReadToEnd(); resu ...

Understanding how to incorporate a URL parameter using HTML and Javascript

I have a web application section where users can search for locations on a map successfully. However, I'd like the text of the location to be displayed in the URL so that users can easily copy and share it for consistent searches. What is the most ef ...

`Troubleshooting Firebase Cloud Functions and Cloud Firestore integration`

I previously used the following Firebase Database code in a project: const getDeviceUser = admin.database().ref(`/users/${notification.to}/`).once('value'); Now, I am attempting to convert it for Firestore. My goal is to retrieve my users' ...

Why is my Laravel Vue CRUD not automatically updating the posts section with new data?

Hey there, I've been working on a project using Laravel 5.6 with Vue.js for CRUD functionality. I'm trying to display the posts I've just added in the posts section without having to reload the entire page. However, my current code is only s ...

What is the best way to assign the value of a specific key in one array as the key in a different array?

I am attempting to retrieve the value feature_1 associated with the key name from the array data. I then aim to set feature_1 as the key of another array asset, with an array as its corresponding value. For example: //input: data: { name: "feature_1" ...

Tips for Successfully Passing an Array to a Fortran DLL via DLLImport Without Any Data Mismatches

I'm currently attempting to pass an array into a Fortran DLL through the following DLLImport statement: [DllImport("MyFortranDLL.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)] static extern void sDTransposeSTDCALL(ref i ...

Implement a 'mock' singleton decorator for the Node class that includes a required initialization method

(Disclaimer: Previous question was deleted due to new fundamental problems, so attempting again with a more logical question). I have a class that requires specific initialization properties: var CustomRequest = require('./request'), ok = r ...

Searching in AngularJS yields unexpected results beyond what was anticipated

I am attempting to retrieve all the users from my Rails application This code is in my Javascript file: var app = angular.module('app'); app.factory('User', function($resource) { return $resource('/users/:id', {id: &apos ...

Tips for leveraging stage 3 functionalities in TypeScript?

Array.prototype.at() is currently in the proposal stage 3. Even after adding "lib": ["ESNext"] to my tsconfig.json, I encountered the error: Property 'at' does not exist on type 'number[]'. Could you shed some light ...

Encountering a 405 Error Code while attempting to upload files with ng-file-upload

In an attempt to incorporate a file upload feature using ng-file-upload, I stumbled upon an example here that served as my reference. Despite everything appearing to function correctly, the issue arises when attempting to upload the file to my local webse ...

Utilizing conditional statements within the array.forEach method to select specific sub-objects within an array of objects

Need help troubleshooting an if statement inside a function that is called by a forEach array loop. My array contains objects, with each object structured like this: arrofobj = [ {"thing_id":"1a", "val": 1, "Type": "Switch","ValType":{"0":"Open","1":" ...

Versatile dataTable designed to seamlessly integrate with various data structures

My task is to develop an ajax dataTable that can handle a variety of data sources with different column names and data types. The challenge lies in the fact that I cannot predefine the column names or data types when coding the dataTable, as each data sour ...

There was a TypeError encountered in a Node application, stating: "Unable to access the 'trim' property of an undefined

Currently, I am developing a JavaScript application that follows the MVC model. In the controllers, there is a userController.js file, and in the models, there is a user.js file which contains a cleanup function. However, I am encountering a TypeError: Can ...

The Grunt connect-modrewrite plugin is experiencing malfunctions

I utilized generator-angular to create my project. I am using HTML5 History. ($locationProvider.html5Mode(true).hashPrefix('!'); For URL rewrite, I am using connect-modrewrite I followed all the steps outlined in the tutorial. Below is my Gru ...

Visit the map only after the promises have been fulfilled

In my current project, I am utilizing the loadash map function for data structuring. The data retrieved consists of a series of IDs that require querying the database and integrating the results into the map before returning. However, the data is delayed i ...

Encountered the error message "A property 'split' cannot be read of undefined" while attempting to run a React Native application

I was able to run a react-native app without any issues yesterday, but today when I tried to run it again, I encountered some problems. After running "npm start" to start metro, I then attempted to run "npx react-native run-android". However, I received th ...