HTML 代码
<div>
<label for="date">Update Time:</label>
<input id="date" ng-model="formData.Updt_Time" ng-value="ts">
</div>
在这里,我尝试将 ng-model 和 ng-value 分配给输入字段,因为我的值(ng-value="ts")ts来 self 的 Controller ,我必须将数据保存到 formData。在表单提交时,我将把 formData 集中的所有值插入到 mySQL 中。
Controller 代码
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);
});
};
});
ng-model 和 ng-value 似乎无法一起工作。有没有解决办法。
最佳答案
首先我有一些建议:
- 您应该开始在 Angular 中使用“controller as”表示法,因为它更具可读性并且不会使 $scope 变得困惑。 (查看 John Papa 的风格指南,以编写更好的 Angular 代码: https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md )
- 如果您打算使用日期做一些事情,我建议您使用 moment.js 库,这将使您免于 javascript 中日期对象的烦恼。
现在,根据我从您的问题中了解到的情况,您正在尝试将文本框的值设置为格式化日期,并将其存储在变量ts中。
要设置文本框的值和模型的值,您可以直接将ts的值直接设置为模型,这将导致 Angular 更新文本框的值.
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;
...
关于javascript - 为单个输入字段设置 ng-model 和 ng-value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38477662/