Angular: When a user clicks, the text from the input fields is added to an array

Initially, I am a bit perplexed as I begin working on this task. I have a straightforward table where the data is fetched from a database and inserted into the DOM using Angular.

The table comprises an option and its corresponding value. My goal is to allow the user to edit these values and then click on a "save" button, triggering an HTTP call to my backend with the updated details.

I've managed to lay down the basics - clicking on a button replaces the cell content with input fields:

Clicking on "Edit":

When clicking on "Cancel," it reverts back to the original state - so far, everything works smoothly.

However, the part that's troubling me now is how to create an array (possibly in JSON format) when the update button is pressed so that I can send it through an HTTP request.

I need a structure where each object in the array/JSON contains the "option" and the "value" for database matching purposes.

Here's a snippet of my HTML:

<div ng-hide="loading" class="table-responsive">    
    <table class="table table-striped table-compact table-bordered">
        <thead>
            <tr>
                <th>Option</th>
                <th>Value</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="setting in settings">
                    <td><< setting.option >> <i class="fa fa-question pull-right pointer" tooltip="<< setting.description >>" ></i></td>
                    <td ng-switch="status">
                                <input ng-switch-when="editable" type="text" class="form-control" value="<< setting.value >>" />
                                <span ng-switch-when="uneditable"><< setting.value >></span>
                    </td>
            </tr>
        </tbody>
    </table>
</div>


<div ng-hide="loading" ng-switch="status">
        <button ng-switch-when="uneditable" ng-click="edit()" class="btn btn-sm btn-info">Edit</button>
        <button ng-switch-when="editable" ng-click="save()" class="btn btn-sm btn-success">Update</button>
        <button ng-switch-when="editable" ng-click="cancel()" class="btn btn-sm btn-danger">Cancel</button>
</div>

Lastly, here's my Angular controller:

app.controller('appSettingsController', function($scope, ApplicationSettings) {

    $scope.settings = {};
    $scope.loading = true;
    $scope.status = 'uneditable';

    // Fetch data for the table
    ApplicationSettings.get()
        .success(function(data) {
            $scope.settings = data;
            $scope.loading = false;
        });

    $scope.edit = function() {
        $scope.status = 'editable';
        $scope.updates = {};
    };

    $scope.cancel = function() {
        $scope.status = 'uneditable';
    };

    $scope.save = function() {

        // Construct Array/JSON of inputs

    };

});

Any suggestions or thoughts on how to proceed? Could it be related to utilizing ng-model?

Answer №1

When editing a table entry, the second column includes an input element tag like this:

<input ng-switch-when="editable" type="text" class="form-control"
 value="<< setting.value >>" />

I believe that the value attribute should be {{setting.value}} instead of << setting.value >>. The former syntax is more appropriate for AngularJS.

To meet your requirements, consider using the ng-model attribute as suggested.

By adding the ng-model attribute, the input element changes to:

<input ng-switch-when="editable" type="text" class="form-control"
 ng-model="setting.value" />

The ng-model handles both displaying and updating the value in the input field through two-way data binding. Any changes made will automatically update the $scope.settings variable without the need for additional code.

One drawback is that if you click cancel, the original values may be lost since any edits are immediately saved. To preserve the initial values before entering edit mode, store them in a separate variable to revert back to them when needed.

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

Detailed breakdown of the code snippet below

Currently, I am diving into the world of Mongodb and finding myself a little perplexed by this particular line of code: mongoose.connection.once('open',function(){ console.log('connection acquired harsh bajpai '); }).on('error&a ...

Can a TypeScript interface be exported as the result of a function?

Looking for a way to convert JSON schema to a Typescript interface in a more efficient manner. Here is an example of what the current method looks like: //Input var scriptSchema = { type: 'object', properties: { src: { type: &apo ...

Navigating through complex immutable entities

I am having trouble working with multidimensional immutable arrays. I would like to make my array immutable, but I'm not sure how to do so. Consider the following data structure: // data { // item { name: someName, todos: [ ...

Exploring the use of the "++" operator in Regular

Is there a way to detect the presence of ++, --, // or ** signs in a string? Any help would be greatly appreciated. var str = document.getElementById('screen').innerHTML; var res = str.substring(0, str.length); var patt1 = ++,--,//,**; var resul ...

What is the best way to choose the initial element in every group using jQuery?

If we have the following HTML input: <p>A</p> <p>B</p> <p>C</p> <div>D</div> <p>E</p> <p>F</p> <p>G</p> We can select B, C, F and G using the following code: $('p + ...

Issues with AngularJS history back button functionality

After extensively researching examples of the AngularJS Back Button event, I have been unable to get any of them to work. Pressing the browser back button does not trigger the event in my code, leaving me puzzled for days. All I am trying to achieve is an ...

What is the most effective method for populating an array with all images from a particular directory?

I recently installed a pdf viewer plugin on my website (check it out here: ), and I have a question regarding its functionality. I am looking to include approximately 60 - 70 pages in this flip book, but I am unsure of how to proceed. I have attempted var ...

Issues with the functionality of socket.io and node.js are causing problems

Currently, I am experimenting with building apps using socket.io and node.js. Specifically, I am working on a basic "log in" application, but it seems to be encountering some issues. Every time I launch the app, a "404 not found" message appears in the Chr ...

Tips for removing duplicate objects from an array

I am utilizing the underscore.js plugin in my code I experimented with it on jsfiddle var basket=[{ "basketitems":[{"items":[]}], "itemdetails":[{ "amountPledged": "100", "bActivity": "Handloom Wo ...

What could be causing my JavaScript code to continuously run in a loop?

Below is the code snippet that I am currently working with: JS <script type="text/javascript"> $(function(){ $('#fgotpwfield').hide(); $('#login_submit').click(function() { $('#form_result').fade ...

Creating routes in JavaScript to split an object like a tree: a comprehensive guide

When I receive a set of filters as a composed object in my express server, I realized that to create the query I need to split each object route into a separate array of keys. For example: $and: { age: [21, 22], name: { $like: "Alice& ...

The art of combining arrays of objects while eliminating duplicates

I am in need of a solution to compare two object arrays, remove duplicates, and merge them into a single array. Although I am relatively new to javascript/Typescript, I have come across some blogs suggesting the use of Map, reduce, and filter methods for t ...

Using Python Webdriver to Execute JavaScript File and Passing Arguments to Functions

How can I execute a JavaScript function and pass arguments to it? value = driver.execute_script(open("path/file.js").read()) I have successfully executed the file, but I am unsure of how to pass arguments to the function within it. Any suggestions would ...

Allow URL to proceed in UI-Router in the absence of a state definition

Exploring the possibilities with Angular UI-Router has been exciting, but I am hoping to find a way for any URL to smoothly pass through the browser and navigate to the page even if it is not specifically defined in the $stateProvider or $urlRouterProvider ...

One of the components in React failed to render even though data was successfully passed to both

I utilized React to create a submenu list. The parent component receives JSON data and passes it down to two child components. However, only one of the child components successfully displays the data while the other fails to do so. Both child components ...

Error loading 'protobuf.js' while retrieving Firestore document

When trying to run a basic node file with Firebase and Firestore, the following code was used: const firebase = require("firebase"); const http = require('http') require("firebase/firestore"); firebase.initializeApp({ apiKey: '...' ...

Display a Bootstrap 5 Modal in a React component based on specified conditions

I'm currently leveraging Bootstrap 5.13 in my react project. I'm looking to implement a Modal window that will be displayed upon form submission, once the backend confirms successful data saving. To achieve this, I've created a separate com ...

Using JQuery to monitor the loading of a newly selected image src attribute

As a newcomer to JavaScript and JQuery, I am facing a challenge that I couldn't find a solution for in other discussions: I have a function that retrieves the path to an image (/API/currentImage) using a GET request and needs to update the src attrib ...

Why is React's nested routing failing to render properly?

click here for image portrayal I am currently attempting to integrate react router, specifically a nested router. However, when I click the links on the contact page, no results are being displayed. Any assistance would be greatly appreciated. For more in ...

Issues with rendering in-line styles in ReactJS after a state update

I'm currently working on implementing a basic state change for a button in React. 'use strict'; class ReactButton extends React.Component { constructor(props) { super(props); this.state = {hovering: false}; } onClick() { ...