AngularJs - 指令来修改输入格式化 [英] AngularJs - Directive to modify input formatting

查看:247
本文介绍了AngularJs - 指令来修改输入格式化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做到以下几点:

我在我的控制器模型日期对象,我希望让用户修改它。
用户应给予两个输入字段。
第一个输入字段应该修改的日期,其他的时间。
两个输入场应在同一日期模型工作

I have a date object in my controller model and I want to let the user modify it. The user should be given two input fields. The first Input field should modify the date, the other the time. Both input field should work on the same date model.

<input ng-model="model.date" date-format="YYYY-MM-DD">
<input ng-model="model.date" date-format="HH:mm:SS">

我没有找到这个结合文献。
通常情况下,NG-模型指令获取输入字段的值照顾。
现在,我要改写我自己的格式此值。
此外,如果用户改变了输入时,改变应该被解析并放回日期对象

I didn't find literature about this binding. Normally the ng-model directive takes care of the value of the input field. Now I want to overwrite this value with my own formatting. Also, if the user changes the input, the changes should be parsed and put back into the date object.

作为香草JS日期操作是一种奇怪的,我用moment.js格式化和分析日期和字符串。

As date manipulation in vanilla js is kind of weird, I used moment.js to format and parse the dates and strings.

我目前的做法是这样的:

My current approach looks like this:

app.directive('dateFormat', function() {
    return {
        restrict: 'A',
        link: function(scope, el, at) {
            var format = at.dateFormat;
            scope.$watch(at.ngModel, function(date) {
                var result = moment(date).format(format);
                el.val(result);
            });
        }
    };
});

然而,这会尽快,因为我想改变在浏览器中输入值突破。
我得到一些楠:NaN的...

However this will break as soon as I want to change the input value in the browser. I get some NaN:NaN...

我的问题是:


  • 如何建模呢?

  • 是这种方法适用于有角的理念还是我在这里做一些奇怪的?

  • 我可以使用NG-模型和我的日期格式的指令一起?

  • 是否有更简单的方法来做到这一点?

推荐答案

一个过滤器是你在找什么:

A filter is what you are looking for:

//In your controller
$scope.modelDate = $filter('date')(dateToFormat, "YYYY-MM-DD");

//In your view
<input ng-model="modelDate" type="text">

话虽这么说,你正在尝试做的是不是太过,因为每当用户写入输入,格式化将中断。您需要使用ngModel,它与指令(一个API)工作,可以直接浏​​览作为连接过程的第四个参数的特殊方式。

That being said, what you are trying to do was not too "off", because whenever the user writes to the input, the formatting will break. You need to use ngModel, which has a special way to work with Directives (an API) and can be browsed directly as a fourth argument in the linking process.

因此​​,对于你code这将是这样的:

So for your code it would be something like this:

return {
  require: 'ngModel',
  link: function(scope, element, attrs, ngModelController) {
    ngModelController.$parsers.push(function(data) {
      //View -> Model
      return data;
    });
    ngModelController.$formatters.push(function(data) {
      //Model -> View
      return $filter('date')(data, "YYYY-MM-DD");
    });
  }
}

的更多信息这里

这篇关于AngularJs - 指令来修改输入格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆