When setting both ng-model and ng-value for a single input field

HTML Markup

<div>
    <label for="date">Update Time:</label>
    <input id="date"  ng-model="formData.Updt_Time" ng-value="ts">
</div>

In this code snippet, I am attempting to assign ng-model and ng-value to the input field. The value (ng-value="ts") is fetched from the controller and will be saved to formData. Upon form submission, all values in formData will be inserted into mySQL.

CONTROLLER CODE

clientApp.controller('formCtrl',function($scope,$http){
    $scope.statuses = ["Active", "Inactive"];
    $scope.cluster = ["East Coast","West Coast","PayPal"]
    // Update Date 
    var currentTime = new Date()
    var yr=currentTime.getFullYear()
    var mnth=currentTime.getMonth()
    var dt=currentTime.getDate()
        if (mnth < 10) {
        mnth = "0" + mnth
        }
        if (dt < 10) {
        dt = "0" + dt
        }

    var hours = currentTime.getHours()
    var minutes = currentTime.getMinutes()
    var seconds = currentTime.getSeconds()

    if (minutes < 10) {
        minutes = "0" + minutes
    }
    if (seconds < 10) {
        seconds = "0" + seconds
    }
    $scope.ts = yr + "-" +mnth+ "-" + dt + " " + hours + ":" + minutes + ":" + seconds + " ";
    //when submit button is clicked 
    $scope.submit = function() {
           alert("Submit Clicked");
           $http.post('/clientPost', $scope.formData).success(function(response) {
                console.log('Data posted successfully');
            })

                    .error(function(data){
                            console.log("There is an error");
                            console.log('Error: ' + data);
                    });
    };
});

However, it appears that the ng-model and ng-value are not functioning together as intended. Is there a workaround to address this issue?

Answer №1

To begin with, I have a couple of suggestions:

  • Consider using the 'controller as' notation in Angular for better readability and to avoid cluttering up the $scope. (Take a look at John Papa's style guide for improving your Angular code: https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md)
  • If you need to work with dates, try using the moment.js library to alleviate the troubles that come with the Date object in JavaScript.

Based on your question, it seems like you want to set the textbox value to the formatted date stored in the variable ts.

You can achieve this by setting the value of ts directly to the model, which will trigger Angular to update the textbox value as well.

HTML
<div>
  <label for="date">Update Time:</label>
  <input id="date" ng-model="formData.Updt_Time">
</div>


JAVASCRIPT
...
var ts = yr + "-" + mnth + "-" + dt + " " + hours + ":" + minutes + ":" + seconds + " ";
$scope.formData.Updt_Time = ts;
...

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

How to run multiple queries in Node.js MySQL with optimal speed

Which method is the most efficient for querying MYSQL and getting the output quickly? console.log('queries finished', results)" Is there a better alternative? Please provide an explanation! Thank you! Method One: var connection = mysql.cr ...

JavaScript - Function is not recognized even though it has been defined, following the completion of a jQuery function

I am encountering an 'Is Undefined' error when running a piece of JavaScript code. https://i.sstatic.net/q3EfY.png < script language = "javascript" type = "text/javascript" > // function added for click on submit - dp0jmr 05/23/20 ...

Searching for regex patterns in a custom column using jQuery DataTables button

Exploring the use of jQuery DataTable to render server-side data, I encountered an issue. While I can search for a single string and render the DataTable accordingly, I am facing difficulties when attempting to match multiple strings using the provided cod ...

What could be causing the issue with clicking on children of jstree not working?

I am encountering an issue with jstree. Once the data is changed, the click event does not work for every subsequent click. I find that I need to refresh the page in order to make it work. Here is a link to the jsfiddle: http://jsfiddle.net/2Jg3B/2121/ I ...

Launching shuttles using HTML and JavaScript

I've been working on an HTML code with JavaScript for a platform validation project. Over the last couple of weeks, I've been diligently coding and testing to ensure everything runs smoothly. However, my code suddenly stopped responding, leaving ...

performing dual queries on identical tables

I am working with two tables: stock_by_month and book. The stock_by_month table stores information on bookId, stockvalue, and reportId, while the book table contains records for BookId, BookTitle, and bookprice. Each month has a unique reportId, such as 1 ...

Establishing a Tiered Assessment Method

I have noticed many questions regarding how to protect and prevent misuse of rating systems for movies, products, etc., but I have not come across any information on how to actually implement it. To clarify, security is not a major concern for me as the in ...

Angular CDKScrollable not triggering events

I'm having trouble making the angular CdkScrollable work when creating my own div: <div class="main-section" id="mainsection" #mainsection CdkScrollable> <div class="content" style="height: 300px; backgr ...

Using AngularJS to access a method in a parent scope from within a directive

In my Angular application, I am utilizing ui-grid. I am looking to implement a custom action on a cell within the grid that will trigger a method from my app. Essentially, this involves calling a method located higher up in the parent hierarchy from a dire ...

Is it possible to pass a variable as an input parameter in the Date constructor when creating a timestamp in Firebase

I'm looking to work with timestamp queries. Note: setSD and setED are part of the Vue object's data, and the firebase function call is within the method. callFirebase: function (){ let startdate = new Date(this.setSD+'T00:00:00&apo ...

The process of updating a column within the same table column

I have a table named t1. table t1 id post_id tags 1 null a 2 1 null 3 1 null 4 null b I am looking to update the tags where post_id matches id. When I tried running a query for this, it returned zero output. In this table, po ...

Activate video playback when scrolling, but ensure it only occurs one time

I've encountered an issue with my script that is meant to play a video when it reaches a certain position on scroll. The problem is, if the video is paused and scrolling continues, it starts playing again. I attempted to use just one scroll function b ...

Error encountered in MySQL Workbench version 6.0: Unable to obtain management access for the administrator

While working with MySQL Workbench 6.0, I encountered an error when trying to view the server status. After searching for solutions on Google and StackOverflow (for example, this result), I have not been able to locate the Server Administration and Workbe ...

My function is not working with jQuery's .append method

As a newcomer to javascript and jquery, I am experimenting with adding html through a javascript function. In an attempt to place the contents of variable "y" at a specific location, I am using a div tag with the id of "Contacts" and trying to append elem ...

Apply a static style to every rendered component just one time

Is there a way for me to individually style each card image only once? For example, I want to apply a transform style via a function in CSS; I want the image to maintain its original value, but when a new component is rendered, that card should have a di ...

Issue with mouse movement in Selenium and Protractor not functioning as expected

Greetings! I am currently facing an issue in my Angular application with Openlayers3 map integration. There is a layer representing a building on the map, and when I try to click on a building during testing, it should trigger a side panel displaying image ...

How do I ensure that in Vue.js, the select element always has the first option selected even when other options are dynamically shown or hidden?

In my Vue app, I have a select element that dynamically shows or hides options based on the user's previous selections. For example: <select id='animal' v-model='values.animal.selected'> <option value='cat' ...

The typescript error TS2339 is triggered by the property 'webkitURL' not being found on the 'Window' type

Currently utilizing Angular 2 in a project that is compiled with TypeScript. Encountering an issue when attempting to generate a blob image: Error TS2339: Property 'webkitURL' does not exist on type 'Window' The TypeScript code causi ...

Error message occurs when creating a pie chart with invalid values for the <path> element in Plottable/D3.js

For those who need the code snippets, you can find them for download here: index.html <!doctype html> <html> <head> <meta charset="UTF-8"> <!-- CSS placement for legend and fold change --> </head> <body ...

Utilizing JSON for effective data storage in database design

In my database, I have a list of campsites. The main table, tblSites, holds unique data such as name, coordinates, and address. It also includes columns for each facility (Toilet, Water, Shower, Electric) where 1=Yes and Null=no. Search queries would look ...