Submit button does not capture Angular ng-model values

Here's a situation with two input fields in a form that I need help with:

<form name="modifyApp" class="form-signin" ng-submit="modify(val)">
   <input type="text" class="form-control" ng-model="val.name" id="appName">
   <input type="number" class="form-control" ng-model="val.number" id="number" min="0" max="65535">
   <button type="submit">Submit</button>
</form>

Upon loading the page, these fields are populated with values from the controller:

angular.module('myApp').controller('modifyAppController', ['$scope', function($scope) {
    function setFields(appName, appNumber){
        document.getElementById("appName").value = appName;
        document.getElementById("number").value = appNumber;
    }

    $scope.modify= function(val){
        console.log(val);
    }
}])

The issue arises when clicking the Submit button. The values are not being registered unless they are manually changed beforehand. For instance, upon hitting the Submit button without any changes, nothing is printed to console. However, modifying either the number or the name results in the value being displayed.

Answer №1

When working with your controller, it is important to properly initialize the val object as shown below:

angular.module('myApp', [])

.controller('updateAppController', ['$scope', function($scope) {

  $scope.val = {
    title: '',
    count: 0
  };

  function populateFields(appTitle, appCount) {
    $scope.val.title = appTitle;
    $scope.val.count = appCount;
  }

  $scope.update = function(val) {
    console.log(val);
  };
}]);

Answer №2

To improve your controller, consider the following changes:

angular.module('myApp').controller('updateAppController', ['$scope', function($scope) {
    $scope.application = {
        name: 'My application',
        version: '1'
    };

    function updateInfo(appName, appVersion){
        $scope.application.name = appName;
        $scope.application.version = appVersion;
    }

    $scope.update = function(){
        console.log($scope.application);
    }
}])

In Angular, avoid directly manipulating DOM values. Instead, use $scope variables which can be accessed in your template.

Answer №3

Instead of complicating things, why not streamline your form by starting with this simple line:

<form name="updateForm" class="form-signin" ng-submit="update()">

Your controller can then be structured like this:

$scope.data = {
  name: '',
  age: 0 //set some default values
}
$scope.update = function(){
    console.log($scope.data)
}

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

I am encountering an error with addToCart, as I am unable to read properties of undefined when trying to use the 'push' function

import { createSlice } from '@reduxjs/toolkit'; const cartReducer = createSlice({ name: 'cart', initialState: { items: [], }, reducers: { addToCart: (state, action) => { state.items.push(action.payl ...

Adding a Fictitious Pair to a JavaScript Object Literal

When I work with object literals in JavaScript, I often encounter syntax errors when adding a new label / value pair without including the trailing comma. This can be frustrating as it's easy to forget to include the necessary delimiter. .draggable({ ...

Is it possible for the background color to change in a sequence every time the page

I'm having trouble figuring out how to create a sequence that changes the background color every time the page is refreshed. I'm comfortable with basic HTML but not so much with JavaScript or CSS. I'm working on a page where I want the backg ...

The URL may change, but the component remains constant when navigating back

My application consists of two primary components: the Project component and MainContainer. The MainContainer component regularly fetches data using a fetchData method. When moving forward, both the URL and component can change dynamically. However, when m ...

What is the best method for displaying over 1000 2D text labels using three.js?

Currently, I am in the process of designing a floor plan that includes over 1000 2D meshes with shapeGeometry and basicMeshMaterial on the scene. I also need to incorporate 2D text within these meshes while ensuring that the text is hidden within the bound ...

The button's URL will vary depending on the condition

As a newcomer to coding, I am seeking guidance on creating a button with dynamic URLs based on user input. For instance, let's say the button is labeled "Book Now" and offers two package options: Standard and Premium. I envision that if a user selec ...

Tips for transferring an array from a php page to a javascript page

In my PHP code, I have an array structured like this: 1) <body onload="addMarkers(<?php print_r($myArray) ?>)"> 2) <body onload="addMarkers(<?php echo json_encode($myArray) ?>)"> Unfortunately, these attempts were unsuccessful. U ...

I'm sorry, but we were unable to locate the module: Error: Unable to find 'fs' in '/usr/src/app/node_modules/jpeg-exif/lib'

Encountering an error when building a react app on production: Module not found: Error: Can't resolve 'fs' in '/usr/src/app/node_modules/jpeg-exif/lib' Node Version: Node version 18 Steps taken in Docker Production: npm install - ...

Are there any missing (or "optional") expressions in handlebars.js?

Currently, I am developing a build script using Node.js. To summarize, the script carries out the following tasks: Prompting the user for essential information such as the project name and description Cloning a template from a Git repository Renaming fil ...

What will occur if I pass a variable through numerous requires()?

Currently, I have the players variable being passed down 3 levels within my NodeJS folder structure. It all starts in server.js file: var players = {}; require('./routines')(players); This is what's inside the routines directory, specific ...

Ever since transitioning to Discord.js 13, why am I suddenly encountering a bug with the messageCreate event?

I'm encountering an issue with my external js file for Events in messageCreate.js. It seems like certain functionalities are not working correctly, even though they were functioning fine with Discord.JS version 12. For instance, when I try to return ...

Converting a JSON array into a singular object using Node.js

I am struggling to convert a JSON array into a single object. Here are the details: Array: [{ "item-A": "value-1" }, { "item-B": "value-2" }] Expected Result: { "item-A": "value-1", "item-B": "value-2" } I have attempted various methods but none have yi ...

Reorganize child JSON objects into a new object that includes a parent ID

Exploring the realm of JavaScript, I am currently delving into Node.JS to interact with an API and save the data in a SQL Server. Utilizing the "request" and "mssql" Node packages for this task as they possess robust documentation and support. My query re ...

There was an error of TypeError found in the views/welcome.ejs file during the e

I have embarked on creating a chat application, where I intend to store data in the following format {"name": "luxii", "chat": "blah blah", "chat": "more blah" } However, the code I wrote is throwing the following error. TypeError: /home/admin/session/v ...

Submit and upload images using POST method in Meteor

I'm just starting out and feeling overwhelmed by the lack of resources on how to upload POST submitted images in Meteor. Is this feature supported out of the box? If not, how should I go about handling it? So far I've broken it down into these s ...

Issue encountered! The command "npm run build" resulted in an exit status of 1 during the deployment of a website via the vercel command

I have been attempting to deploy a website on Vercel from my VSCode command line using the following command: vercel Upon executing this command, I receive the following output: https://i.sstatic.net/JK9CY.png When I run: vercel logs demo-minting-fronten ...

Leveraging External Libraries in React Applications

Currently integrating d3 with React and facing a challenge where specific d3 functions require access to certain variables/objects. The goal is to trigger one of these functions upon the componentWillReceiveProps() lifecycle method being invoked. Below i ...

What is the best way to incorporate NoFollow attributes into the external links on my Weebly website?

It's frustrating that Weebly doesn't offer a way to make external links noFollow. After reaching out to them with no success, I took matters into my own hands and searched for a solution online. <script src='http://ajax.googleapis.com/aj ...

"An issue has been detected in the Entry module, which cannot be located in

My journey into JavaScript is just beginning, as I diligently follow a well-structured node tutorial available on Github. Despite my best efforts in all the modules, I keep encountering an error message whenever I run yarn dev:wds. ERROR in Entry modu ...

Using Bootstrap 4 beta for Form Validation

I'm struggling to grasp the concept of building validation forms. The bootstrap documentation includes a JS code snippet (referred to as starter code) like the one below: <script> // Example starter JavaScript for disabling form submissions if ...