javascript - HTML 日期字段无法设置回来自后端的日期字段

标签 javascript html angularjs momentjs

我有一个 HTML 日期字段。 我有一个创建页面,我在其中将日期插入 MySQL 数据库 我有一个编辑页面,我在其中获取日期并设置回输入字段。

<input id="dob" name="dob" type="date" placeholder="Enter date of birth" class="form-control" ng-model="user.dob"/>

JS

function loadUserById() {
        ApiService.getById($scope.id).then(function(response) {
            $scope.user = response.data[0];
            $scope.user.password1 = response.data[0].password;

            if($scope.user.dob) {
                var date = new Date($scope.user.dob);
                $scope.user.dob = moment(date).format("MM/DD/YYYY");
            }
        }, function(error) {
            console.log(error);
        });
    }

问题

我将此字段中的日期插入到 MySQL 数据库中,并将其格式化为 YYYY-MM-DD 格式。然后我格式化为 mm/dd/yyyy 格式并尝试在 HTML 日期字段中设置它。

但是它抛出一个错误:

angular.js:14642 Error: [ngModel:datefmt] http://errors.angularjs.org/1.6.5/ngModel/datefmt?p0=06%2F03%2F2018
at angular.js:88
at Array.<anonymous> (angular.js:25252)
at angular.js:29245
at m.$digest (angular.js:18202)
at m.$apply (angular.js:18480)
at l (angular.js:12501)
at XMLHttpRequest.s.onload (angular.js:12655)

最佳答案

得到答案。 需要使用 ng-value 然后它会自动将日期设置到字段中。

function loadUserById() {
        ApiService.getById($scope.id).then(function(response) {
            $scope.user = response.data[0];
            $scope.user.password1 = response.data[0].password;

            if($scope.user.dob) {
                var date = new Date($scope.user.dob);
                $scope.user.dob = moment(date).format("YYYY-MM-DD");
            }
        }, function(error) {
            console.log(error);
        });
    }


<input id="dob" name="dob" type="date" ng-readonly="readOnly" placeholder="Enter date of birth" class="form-control" ng-model="user.dob" ng-value="user.dob"/>

关于javascript - HTML 日期字段无法设置回来自后端的日期字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50850417/

相关文章:

javascript - AngularJS 和 Bootstrap 工具提示的范围问题

angularjs - 在 KendoGrid 模板中使用函数

javascript - 与 attr() 类似的函数,带有回调函数的参数

javascript - 如何获取偶数数组索引并更改其背景颜色

html - 图像在旋转木马中被拉伸(stretch)

html - 如何禁用图像上的突出显示

AngularJs UI 路由器 - 具有多个 URL 的一种状态

javascript - 如何使用 javascript 以编程方式设置多选框元素的值(复数)?

javascript - Paypal Express Checkout PHP,将其加载到花式框而不是弹出窗口

html - 使用 AngularJS 从按钮单击的下拉列表中选择所有选项