Having trouble passing input values from the view to the controller in Angular?

Having an issue with sending data to the controller via my view. Below is a snippet of the code:

<form ng-submit="submitMessage()"> 
                <div class="form-group">
                    <input type="number" class="form-control input-sm" name="id_user" ng-model="messageData.id_user" value={{currentUser.id}} >
                </div>

                <div class="form-group">
                    <input type="number" class="form-control input-sm" name="id_thread" ng-model="messageData.id_thread" value={{messages[0].id_thread}}>
                </div>

                <!-- COMMENT TEXT -->
                <div class="form-group">
                    <input type="text" class="form-control input-lg" name="message" ng-model="messageData.text" placeholder="Write your message">
                </div>

                <!-- SUBMIT BUTTON -->
                <div class="form-group text-right">
                    <button type="submit" class="btn btn-primary btn-lg submit-btn">Submit</button>
                </div>
            </form>

For handling this in my controller:

angular.module('messageCtrl', []).controller('messageController', function($scope, $http, Message, $stateParams) {
// object to hold all the data for the new comment form
$scope.messageData = {};

//get id from route
var id = $stateParams.id;
// get all the comments first and bind it to the $scope.comments object
// use the function we created in our service
// GET ALL COMMENTS ==================================================
Message.get(id).then(successCallback);
function successCallback(data) {
    $scope.messages = data.data;
}

// function to handle submitting the form
// SAVE A COMMENT =====================================================
$scope.submitMessage = function() {
    // save the comment. pass in comment data from the form
    // use the function we created in our service
    console.log($scope.messageData);
    Message.save($scope.messageData).then(successCallback2, errorCallback);
    function successCallback2(getData) {
        $scope.messages = getData.data;
        Message.get(id).then(successCallback);
    }

    function errorCallback(data) {
        console.log(data);
    }

};



});

Encountering issues whereby only the 'text' field is sent to the controller when attempting to send data. The aim is to have the two initial inputs hidden but still contain predefined values. However, including these values within the "value" attribute leads to errors as follows:

angular.js:3505 The specified value "{{messages[0]['id_thread']}}" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)?
angular.js:3505 The specified value "{{currentUser.id}}" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)?

The puzzling aspect here is that upon inspecting the values in the developer tools, they are numerical. Any insights on how to resolve this dilemma would be greatly appreciated.

Answer №1

When initializing the controller, ensure that you have the currentUser.id value ready to use. If so, you can set up the messageData object like this:

$scope.messageData = { id_user: currentUser.id };

If there is a delay in loading the currentUser value, make sure to assign it back to the messageData object once it's available:

$scope.messageData.id_user = currentUser.id;

By removing the value attribute, you should be able to resolve the error. This same approach can be applied to the id_thread input as well.

Answer №2

To address this issue, it seems necessary to remove value={{currentUser.id}} and value={{messages[0].id_thread}}, as the ng-model is responsible for setting the current value. Instead, initialize messageData with the initial values 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

Is it possible to save edits made to CKEDITOR by clicking a button located outside of the editor?

I am having an issue with inserting HTML code into my CKEDITOR. I have a button on the page that, when clicked, calls: editor.insertElement(link); After inserting the HTML code correctly into the editor, any changes made (such as clicking the 'show ...

Using regular expressions in AngularJS to structure input data

I need to extract the first two tokens from some data formatted like this using regex. For instance, AB.JKL.MNO.XYZ => AB.JKL AB.JKL.MNO.XYZ KJ.KJLJ.KD.IUOI KLJ.LK.LJ.JL.OLJ.JLL Note: Although I can achieve this using AngularJS expression in the html ...

Find strings that contain some text other than Angular expressions using Regex

I recently discovered a need to identify strings in our projects that are not AngularJS expressions due to expanding into multiple languages. This includes any string that is not completely enclosed in curly braces. My goal is to create a regex pattern th ...

What makes CVE-2021-33623 susceptible to ReDoS attacks?

CVE-2021-33623 points out that the code snippet below (addressed in this commit, along with test cases) is susceptible to ReDoS vulnerabilities: trimNewlines.end = string => string.replace(/[\r\n]+$/, ''); What makes it prone to ReD ...

Can someone assist me in figuring out how to solve selecting multiple radio buttons at once

<script type="text/javascript"> let x = "1.html"; let y = "2.html"; function redirectPage(form){ for(let i=0; i<form.length; i++) { if(form.answerq[i].checked && form.answerw[i].checked && f ...

Adding content to a text field and then moving to the next line

I am looking to add a string to a text area, followed by a new line. After conducting some research, here are the methods I have attempted so far but without success: function appendString(str){ document.getElementById('output').value += st ...

Validating phone numbers in Saudi Arabia for both mobile and landlines

I've been struggling to validate a Saudi Arabia phone number on my Bootstrap form, but I keep running into an invalid error. Here is the current regex pattern I am using: /^(009665|9665|\+9665|05|5)(5|0|3|6|4|9|1|8|7)([0-9]{7})$/ function ch ...

Is there a way to programmatically prevent the back button from functioning if the previous route pathname in React was 'Login'?

When it comes to navigating back on previous pages, the traditional back button is typically used instead of relying solely on the navigation bar. However, I am currently looking to disable this feature specifically when the next previous route in line is ...

AngularJS is capable of executing conditional logic using the if/else statement

I am attempting to set the inputLanguage value to 'en' and encountering an error that says english is not defined. Here is the code snippet from my alchemy.js file: module.exports = function(Alchemy) { Alchemy.language = function(inText, inp ...

Verify whether a specific value exists in my React array; if it does, display a specific component

I need to display different components based on the following criteria: Whether the items contain a specific value And if all 10 items have that value const DisplayComponents = ({ data }: Props) => { const filteredItems = data.items?.filter( ( ...

Retrieving external response data within a nested $http request

Excuse me as I am new to working with AngularJS. I am trying to figure out how to properly handle a nested $http call in my code, $http({ method: 'GET', url: host1, params: { 'format': 'json', } }).then(function ...

What is the best method for incorporating card components from Stripe into a Vue.js application?

I am currently facing an issue with implementing Stripe in my Vue.js project. Despite following the documentation provided, I am encountering errors such as "stripe is not defined" and "Uncaught ReferenceError: h is not defined". Initially, I created a pa ...

Transferring data to ng-model within ng-repeat loop

I am facing an issue with a form that is supposed to pass its inputs to ng-model before saving them into the database. One of the inputs is a dynamic value, specifically a pre-generated code retrieved from a database table. <div class="form-group" ng-r ...

What is the best way to verify the accuracy of my model when it includes an array property?

One of the challenges I am facing is dealing with a class that has an array property in MVC. public class MyClass { public int Contrato_Id { get; set; } public string Contrato { get; set; } public int Torre_Id { get; set; } public string T ...

Error: Unable to register both views with identical name RNDateTimePicker due to Invariant Violation

Encountering an issue while attempting to import: import DropDownPicker from 'react-native-dropdown-picker'; import DateTimePicker from '@react-native-community/datetimepicker'; <DropDownPicker zIndex={5000} ...

What is the best way to manage a batch of files in a response from an Ajax POST request?

Currently, I am utilizing the OGRE web client to convert GeoJSON text data into ESRI shapefiles by making a POST request with Ajax. var data = { "type": "FeatureCollection", "features": [{ "type": "Feature", "geometry": { "type": "Point", "coord ...

When utilizing Route.get() with an express app, an error occurred as a callback function was expected, but instead, an [

My health.js file contains the following code: var health = function(req, res, done) {}; health.prototype.endpoint = function(req, res, done) { let http_status = 200; console.log("--- Sending health endpoint status of %s", http_status); res.se ...

Exploring the power of async/await in combination with map or foreach

I am facing a challenge in retrieving multiple product prices from my database. I had initially thought of using the map or forEach methods to iterate through them and add up the prices to a variable as shown below: // Get Total exports.getTotal = (req,re ...

A guide to obtaining radar chart coordinates by utilizing the getValueForDistanceFromCenter method in Chart.js

I've been experimenting with creating radar charts using Chart.js. I have a good grasp on the basics, as shown in the simple chart below, but I'm looking to utilize the x y coordinates of the graph to position text directly on the canvas. After ...

Searching for the best way to patiently wait for an animation to finish in angular.js

I have implemented animate.css for animations on my website, but I am facing an issue where I want a specific animation to trigger immediately after another one has completed. Here is the CSS code snippet: .pageRenderer.ng-enter{ animation: fadeIn 1s ...