简单angularjs日期输入 [英] Simple angularjs date input

查看:155
本文介绍了简单angularjs日期输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个编辑页面为事件和我的领域之一是日期。在一些浏览器似乎像一个普通的文本框(IE8),但在Chrome中则显示DD / MM / YYYY,如果你点击它,它有设定日期一些附加选项。

我的问题是,虽然它不填充现有的日期的编辑页面上(我想象的,因为它不是正确的格式?)。 MVC的控制器以这种格式返回数据2014-03-08T00:00:00。(只使用基本的CRUD控制器动作)

 <表格名称=形式级=形横>
< D​​IV CLASS =控制组NG-CLASS ={错误:form.EventDate $无效}>
        <标签类=控制标签为=EVENTDATE>事件日期和LT; /标签>
        < D​​IV CLASS =控制>
            <输入类型=日期NG模型=item.EventDateID =EVENTDATE>
        < / DIV>
    < / DIV>
< D​​IV CLASS =表单行动>
        <按钮NG点击=保存()级=BTN BTN-小学>
            {{行动}}
        < /按钮>
        < A HREF =#/级=BTN>取消< / A>
    < / DIV>
< /表及GT;

我已经看到了使用指令和手表不少帖子,但看起来很复杂。我本来还以为已经格式化模型数据,以便它显示在正确的格式,按预期工作的一个比较简单的方法。我不介意Chrome提供了比其他浏览器不同的体验 - 它只是一个简单的内部用户的网站。我只是不喜欢它没有prepopulating日,当我编辑记录。


解决方案

如果你想填充字段的初始值,那么下面的工作。

  //控制器:
$ scope.myDate =新的日期(2014-03-08T00:00:00');// HTML:
<输入类型=日期NG-的init =模型=(数值指明MyDate |日期:'YYYY-MM-DD')NG模型=模式/>

不过,我强烈建议创建一个自定义日期字段指令。

自定义输入字段指令具有以下优点:


  1. 双向模型和视图之间的结合。
     例如,当你输入的输入字段有效日期,它会自动分配一个javascript日期模型;当你指定一个有效的JavaScript日期为模型,它会自动在文本字段进行格式化。

  2. 表单验证支持。当你输入一个无效的日期,你可以设置$错误标志,它可以在您的视图绑定使用(即显示错误消息)。设置错误标志还将设置的形式。$有效为false,这样就可以有条件地提交表单到服务器。

有实现自定义日期指令时要考虑三个基本的​​东西:


  

      
  1. 一个解析器,它将分析输入的文本,并返回模型
        (在这种情况下,一个JavaScript日期)。

  2.   
  3. 系统格式化,将格式化模型,并在文本字段中显示。

  4.   
  5. ,可在用户界面中使用的可选的验证标志的设置
         自定义表单验证。

  6.   

日期指令:

  myApp.directive('的DateField',函数($过滤器){
  返回{
      要求:'ngModel',
      链接:功能(范围,元素,ATTRS,ngModelController){
           ngModelController。$ parsers.push(功能(数据){              //查看 - >模型
              VAR日期= Date.parseExact(数据,'YYYY-MM-DD');              //如果日期字段是不是有效的日期
              //然后通过调用$ setValidity设置日期错误标志
              ngModelController $ setValidity。(日期,日期!= NULL);
              返回日期== NULL?未定义:日期;
           });
           ngModelController。$ formatters.push(功能(数据){
              //模式 - >视图
              返回$过滤器('日期')(数据,YYYY-MM-DD);
           });
       }
    }
});

请注意:对于解析日期,该指令使用 Date.js (外部库)

CSS:

  .error {
  颜色:红色;
}
.error界{
  边界:2px的固体红;
}

HTML

 <形式NAME =myForm会>
     <输入纳克级={'错误边界:myForm.myDate $ error.date}类型=日期
            NAME =数值指明MyDateNG模型=数值指明MyDate日场/>
              <跨度NG秀=。myForm.myDate $ error.date级=错误>
                  请输入有效的日期!
              < / SPAN>
         < BR />原始数据:{{数值指明MyDate}}
         < BR />很好地格式化:{{数值指明MyDate |日期:'YYYY,MMMM DD'}}
         < BR />是有效期? {{!myForm.myDate。$ error.date}}
         < BR />即形式是否有效? {{myForm会$有效}}
< /表及GT;

控制器:

  myApp.controller(Ctrl键,功能($范围){
    $ scope.myDate =新的日期(2014-03-08T00:00:00');
});

演示JS小提琴 Date.js

演示JS小提琴 Moment.js

I have an edit page for an event and one of my fields is a date. In some browsers it seems to act like a plain text box (IE8), however in chrome it displays "dd/mm/yyyy" and if you click on it it has some additional options for setting the date.

My issue though is on the edit page it's not populating the existing date (I imagine because it's not in the correct format?). The MVC controller returns the data in this format "2014-03-08T00:00:00" (just using basic CRUD controller actions).

<form name="form" class="form-horizontal">
<div class="control-group" ng-class="{error: form.EventDate.$invalid}">
        <label class="control-label" for="EventDate">Event Date</label>
        <div class="controls">
            <input type="date" ng-model="item.EventDate" id="EventDate">
        </div>
    </div>
<div class="form-actions">
        <button ng-click="save()" class="btn btn-primary">
            {{action}}
        </button>
        <a href="#/" class="btn">Cancel</a>
    </div>
</form>

I've seen quite a few posts on using directives and watches, but that seems complicated. I would have thought there would have been a relatively simple way of formatting the model data so that it displays in the right format and works as expected. I don't mind if Chrome gives a different experience than other browsers - it's just a simple internal user website. I just don't like that it's not prepopulating the date when I edit a record.

解决方案

If you want to populate the field with an initial value, then the following will work

//Controller:
$scope.myDate = new Date('2014-03-08T00:00:00');

//HTML:
<input type="date" ng-init="model=(myDate | date:'yyyy-MM-dd')" ng-model="model" />

However, I strongly recommend creating a custom date field directive.

A custom input field directive offers the following benefits:

  1. Two-way binding between the model and the view. For example, when you enter a valid date in the input field, it will automatically assign a javascript date to the model; and when you assign a valid javascript date as the model, it will automatically format it in the text field.
  2. Form validation support. When you enter an invalid date, you can set an $error flag, which can be used in your view bindings (i.e. displaying an error message). Setting an error flag will also set form.$valid to false so that you can conditionally submit the form to the server.

There are three basic things to consider when implementing a custom date directive:

  1. A parser that will parse the input text and return the model (in this case, a javascript date).
  2. A formatter that will format the model and display it in the text field.
  3. Setting of an optional validation flag which can be used in the UI for custom form validation.

Date Directive:

myApp.directive('dateField', function($filter) {
  return {
      require: 'ngModel',
      link: function(scope, element, attrs, ngModelController) {
           ngModelController.$parsers.push(function(data) {

              //View -> Model
              var date = Date.parseExact(data,'yyyy-MM-dd');

              // if the date field is not a valid date 
              // then set a 'date' error flag by calling $setValidity
              ngModelController.$setValidity('date', date!=null);
              return date == null ? undefined : date;
           });
           ngModelController.$formatters.push(function(data) {
              //Model -> View
              return $filter('date')(data, "yyyy-MM-dd");
           });    
       }
    }
});

Note: For parsing dates, this directive uses Date.js (an external library).

CSS:

.error {
  color:red;
}
.error-border {
  border: solid 2px red;
}

HTML:

<form name="myForm">
     <input ng-class="{'error-border': myForm.myDate.$error.date}" type="date"
            name="myDate" ng-model="myDate" date-field />
              <span ng-show="myForm.myDate.$error.date" class="error">
                  Please enter a valid date!!!
              </span>             
         <br /> Raw Date: {{myDate}} 
         <br /> Formatted Nicely: {{ myDate | date:'yyyy, MMMM dd'}}    
         <br /> Is Valid Date? {{ !myForm.myDate.$error.date}}
         <br /> Is Form Valid? {{ myForm.$valid }}
</form>

Controller:

myApp.controller('ctrl', function($scope) {
    $scope.myDate = new Date('2014-03-08T00:00:00');
});

Demo JS Fiddle with Date.js
Demo JS Fiddle with Moment.js

这篇关于简单angularjs日期输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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