【问题标题】:Having ng-model and ng-value set for the single input field为单个输入字段设置 ng-model 和 ng-value
【发布时间】:2016-07-20 09:40:41
【问题描述】:

HTML 代码

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

在这里,我尝试将 ng-model 和 ng-value 分配给输入字段,因为我是 ts 的值(ng-value="ts")来自我的控制器,我将不得不将数据保存到 formData。在提交表单时,我会将设置的 formData 中的所有值插入到我的 mySQL 中。

控制器代码

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 似乎不能一起工作。有没有解决办法。

【问题讨论】:

  • 将输入模型引用设置为 $scope,如

标签: javascript mysql angularjs


【解决方案1】:

首先我有一些建议:

  • 您应该开始在 Angular 中使用“控制器作为”表示法,因为它更具可读性并且不会弄乱 $scope。 (查看 John Papa 的风格指南以编写更好的 Angular 代码:https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md
  • 如果您打算对日期做一些事情,我建议您使用 moment.js 库,它可以让您摆脱 javascript 中的 Date-object 的烦恼。

现在,根据我从您的问题中了解到的情况,您正在尝试将文本框的值设置为格式化日期,并将其存储在变量 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;
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-31
    • 2019-06-02
    • 1970-01-01
    • 1970-01-01
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多