绑定AngularJS中的input [date]和Moment.js

ial*_*eev 9 javascript angularjs momentjs

为了制定问题,我准备了简化的例子:

...
<input type="date" ng-model="selectedMoment" />
...
<script>
 angular.module('dateInputExample', [])
     .controller('DateController', ['$scope', function($scope) {
       $scope.selectedMoment = moment();
        //...more code...
     }]);
</script>
Run Code Online (Sandbox Code Playgroud)

基本上,我只需要在模型(moment.js的日期)和视图(输入[日期]字段)之间进行绑定才能正常工作 - 更新模型时更新日期输入,反之亦然.显然,尝试上面的例子会给你带来错误,模型不是Date类型.

这就是为什么我要问经验丰富的AngularJs开发人员,我该如何正确实现这种绑定?

任何建议表示赞赏.

Gor*_*pur 3

您可以创建过滤器,如下所示:

myApp.filter('moment', function() {
    return function(input) {
        return moment(input);
    };
});
Run Code Online (Sandbox Code Playgroud)

您可以选择将参数传递给过滤器并使其调用各种矩函数。看看角度过滤器,我相信您会想到适合您需求的东西。