【问题标题】:Binding between input[date] and Moment.js in AngularJSAngularJS 中 input[date] 和 Moment.js 之间的绑定
【发布时间】:2014-11-25 13:27:47
【问题描述】:

为了提出问题,我准备了简化的例子:

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

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

这就是为什么我要问有经验的 AngularJs 开发人员,我怎样才能正确地实现这个绑定?

任何建议表示赞赏。

【问题讨论】:

  • @DavidThomas,感谢您的建议,我更新了问题,听起来不那么主观。

标签: javascript angularjs momentjs


【解决方案1】:

创建一个解析日期到时刻并格式化时刻到日期的指令。

下面的基本示例(将通过错误处理进行扩展)

myApp.directive('momentInput', function () {
    return {
        link: function(scope, elm, attrs, ctrl) {
            ctrl.$parsers.push(function(viewValue) {
                return moment(viewValue);
            });
            ctrl.$formatters.push(function(modelValue) {
                return modelValue.toDate();
            });
        },
        require: 'ngModel'
    }
});

【讨论】:

    【解决方案2】:

    您可以像这样创建过滤器:

    myApp.filter('moment', function() {
        return function(input) {
            return moment(input);
        };
    });
    

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

    【讨论】:

      【解决方案3】:

      建议的解决方案都不适合我。我遇到了同样的问题并解决了:

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

      【讨论】:

        【解决方案4】:
        <input type="date" /> 
        

        需要具有特定格式的字符串,或(可能)JavacSript Date() 对象。 http://www.w3schools.com/html/html_form_input_types.asp

        所以你不能真的像那样使用 momentjs 对象。

        如果您想得到字符串作为结果,只需将输入与type="date" 一起使用。 如果你想拥有 momentjs 加上格式和其他东西,你必须创建自己的指令或过滤器。

        【讨论】:

          【解决方案5】:

          提交时拉取原始格式,将其更改为新格式。

          html

          <input type="date" ng-model="input.NewEventDate" >  <button type="button" class="btn btn-success" ng-click="add()">submit</button>
          

          javascript

          $scope.add = function(){
          $scope.input.NewEventDate = moment($scope.input.NewEventDate).format("DD-MM-YYYY");
          }
          

          【讨论】:

            猜你喜欢
            • 2012-11-07
            • 2016-05-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-04-28
            • 2015-11-18
            • 2015-07-23
            • 1970-01-01
            相关资源
            最近更新 更多