user2860954 user2860954 - 4 months ago 16
AngularJS Question

Having ng-model and ng-value set for the single input field

HTML CODE

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


Here i am trying to assign ng-model and ng-value to the input field since i m the value(ng-value="ts") this ts would be coming from my controller, and i will have to save the data to formData. On form submit i will be inserting all the values in the set formData to my 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);
});
};
});


How ever the ng-model and ng-value doesn't seem to work together. Is there a workaround.

Answer

First of I have a few recommendations:

  • You should start using the 'controller as' notation in Angular, as it is more readable and does not clutter up the $scope. (Check out John Papa's style guide for writing better Angular code: https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md)
  • If you are going to do some stuff with dates, I recommend using the moment.js library, which will save you from the annoyance that is the Date-object in javascript.

Now, from what I understand from your question, you are trying to set the value of the textbox to be the formatted date, which you stored in the variable ts.

To set the value of the textbox and also the value of the model, you could simply set the value of ts to the model directly, which would then cause Angular to update the value of the textbox.

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;
...