the input value does not get sent after updates are made on the form

My webpage contains a bs-table that retrieves data from an API call. When a row is clicked, another API call is made to fetch the data for that specific row from the database. The retrieved data is then stored in a scope variable and rendered on the page.

$('#table').on('click-row.bs.table', function (e, row, $element) {

                $('.success').removeClass('success');
                $($element).addClass('success');

                var indexId = $table.find($element).data('index');
                var rowData = $table.bootstrapTable('getData')[indexId];
                $scope.id = rowData.id;

                $http.get(url + $scope.id)
                        .then(function (res) {
                            $scope.rowData = res.data.model;
                            console.log($scope.rowData);
                            $scope.rowKeys = Object.keys($scope.rowData);
                        });
                $scope.$apply();

            });

html:

<form style="padding: 15px" ng-submit="submitForm()">
        <div class="form-group row">
               <div ng-repeat="k in rowKeys | filter: '!id'" ng-model="rowValue">
               <label for="rowValue"  class="col-sm-2">
               <!--{{k | hide:'.name'}}:-->
               {{k }}:
               </label>
               <div class=" col-sm-2">
               <input class="form-control rowValue"  id="rowValue"  value="{{rowData[k]}}"/>
               </div>
          </div>
    </div>
   <button type="submit" class="btn btn-default" ng-if="rowData" >Submit</button>

After making changes in the form fields, I want to submit the updated data back using ng-submit.

 $scope.submitForm = function() {

        $scope.$watch('rowData', function(newValue, oldValue) {
                console.log('being watched oldValue:', oldValue, 'newValue:', newValue);
            }, true);

        $http({
            method  : 'PUT',
            url     : url + $scope.id,
            data    : $scope.rowData, //form
            headers : {'Content-Type': 'application/json'}
        })
        .then(function (res) {
                //console.log(res);
                //console.log($scope.rowData);
                return res;
            });
    };

I have implemented a $watch to detect changes in the scope variable, but the issue is that the console log shows the same values for both oldValue and newValue. Can anyone help me identify where I may be going wrong? Any assistance would be appreciated.

Answer №1

The values are not being bound to any variable. Try replacing value="{{rowData[k]}}" with ng-model="rowData[k]" in your input element.

Answer №2

The issue lies in calling $scope.$apply(); prematurely, before the request has completed. To resolve this, make sure to place $scope.$apply(); inside the then() callback function.

$http.get('data').then(function(response){
    //process data
    $scope.$apply();
});

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

Learn how to incorporate the prettier command into your coding workflow by adding it as a devDependency before committing code or

I am currently engaged in a React project. I am looking to set up autoformatting on save in my Visual Studio Code. However, I prefer not to adjust the settings within VSCode itself due to the variation in configurations among users. Instead, I want to ach ...

What is preventing me from inserting a variable into quotes without needing to use a plus sign?

I'm attempting to create a sub-pattern and display it on the screen using res.send as shown below: app.get('/r/:something', (req, res) => { const { something } = req.params; res.send('<h1>Viewing ${something} on the scr ...

Trigger the UseEffect() function in a Material UI Dialog only when the dialog is open

In my project, I have a parent component that includes a Material UI Dialog as a child component. The purpose of this dialog is to fetch and display data from a REST API. Currently, I am using the UseEffect() function in the Dialog component to achieve th ...

Unexpected TypeError occurred when trying to Fetch data from an Express Server hosted on Window object

Error Message : Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Invalid name Feeling stuck as I looked around, unsure of what's causing this issue. My goal is to develop a website that can eventually make a ...

Incorporating Redux Object into Props in a React Functional Component: A Step-by-Step Guide

Looking for assistance with utilizing the "user" object from reduxReducer within a functional component. To access this object, I am currently using mapStateToProps in the following way: const mapStateToProps = (state) => ({ login: state.login, } ...

Having trouble fetching the value of the scope/elm in AngularJS

I am having trouble triggering an event after the user finishes typing in an input field and I am struggling to retrieve the entered value. Below is the code snippet: Javascript var subtitlesApp = angular.module('subtitlesApp', ['ngResour ...

Why are new lines being added to my package.json file, and what is their purpose?

I am the maintainer of an npm package and I've noticed that there are entries being added to package.json with underscore characters. These entries include information like the package's raw URL, specifications, and locations. "_args": [ [ ...

AJAX request encounters error when trying to send file, receiving a 'blob' error message

I've been struggling with an AJAX request that is supposed to send a file to my controller, where it should be read and then a sorted array returned to the front-end. Unfortunately, I keep getting stuck on an error related to a 'blob' not be ...

Preventing Context Menu from Appearing on Long Click in HTML5 Games

I'm attempting to utilize a similar technique as demonstrated in this stackoverflow post: How to disable the 'save image as' popup for smartphones for <input> However, I am encountering an issue where my button is not displaying at ...

Implementing ordering and limiting of elements in NestJS TypeORM relations

I am new to typeorm and relationships. I am currently facing some challenges and feeling a bit confused. I have a question regarding sorting relations in typeorm by id or createdDate without explicitly mapping them and limiting the number of elements. Here ...

Error: The <Class> cannot be accessed until it has been initialized

I have a basic autoloader method that initializes and returns an instance of a class using require() The require statement includes some logic that requests information from a database and checks if the class exists in the filesystem. let elementClass = r ...

What is the best way to export assets into a React Native JS file?

After watching a video on YouTube, I noticed that at 3:20 the individual in the video quickly exported multiple assets into a file without providing any explanation. Can someone please view this specific moment in the video and clarify how this person mana ...

The content was denied from being shown in a frame due to the setting of 'X-Frame-Options' to 'same origin' in React and oAuth

Every time I try to authorize within the frame using an app that utilizes oAuth2 for authorization, I encounter the following error: The request was refused because it tried to open a page in a frame with 'X-Frame-Options' set to 'same orig ...

Upon clicking the button, input numbers into multiple number type inputs

I recently implemented a button in my application that increments the value of input type='number' after it is clicked. While everything seems to be working fine, I noticed that the numbers start from 0 instead of 1. Is there a way for me to ens ...

The public folder in Node.js is known for its tendency to encounter errors

I'm facing an issue with displaying an icon on my website. Here is the current setup in my code: app.js const http = require('http'); const fs = require('fs'); const express = require('express') const path = require(&apo ...

The y-axis max property in Highcharts does not effectively hide plot bands and labels

I have set up two separate jsfiddles to demonstrate my issue. The first jsfiddle represents the desired behavior, while the second one displays the problem I am encountering. In the first jsfiddle (https://jsfiddle.net/n5ua6krj/1/), the y-axis[0] does not ...

Add both single (' ') and double (" ") quotes within the `document.querySelector` code

Given an array of attributes like the following: let elementsArray = [ '[name="country_code"]', '[name="user_tel_code"]', '[name="countryCode"]' ]; If I aim to iterate through them using a ...

Is it possible for the router to hold off until a promise is fulfilled before proceeding?

After implementing the code snippet provided by express router, an error occurs when trying to use another async function. The specific error message is: Error: Can't set headers after they are sent. Interestingly, upon removing the line await anot ...

React displaying an error indicating that the setTimeout function is undefined?

While attempting to integrate the XTK library with React, I encountered an issue where it kept throwing an error stating that the setTimeout function is not a valid function. Surprisingly, my code appears to be flawless and works perfectly fine when used d ...

I am setting up two data picker fields: the first one should display the date as 01/01/2022, while the second field should show today's date

https://i.sstatic.net/jsTme.png In my project, I am working on setting up 2 input date fields: 1.1. The first field is for the start date and it should automatically display as: 01/01/current-year(For example, if the current year is 2022, then it would sh ...