2015-09-07 99 views
3

发展新世纪通过离子移动应用格式的输入日期,我有这样的HTML:如何使用角1.3和进一步

<input type="date" ng-model="schedule.start" 
        name="startDate" 
        date-to-format /> 

我有这样的指令,旨在对输入内格式呈现的日期标签

.directive('dateToFormat', function ($filter) { 
     return { 
      restrict: 'A', 
      require: 'ngModel', 
      link: function (scope, el, attrs, ctrl) { 
       ctrl.$parsers.push(function (data) { 
        return data; 
       }); 
       ctrl.$formatters.push(function (data) { 
        return $filter('date')(data, 'EEE dd MMMM yyyy'); 
        // error => filter returns a string, not a date object 
       }); 
      } 
     }; 
    }); 

但是,自从Angular 1.3以来,格式化程序必须返回一个Date对象而不是字符串等价物。使用

典型的错误这个指令:

Expected `mon. 07 september 2015` to be a date. 

如何使用角1.3和进一步格式的日期?
如果我包裹$filter围绕new Date(...),我失去了自定义格式...

Plunkr再现问题:http://plnkr.co/edit/eMIHWjtwHSPLxBBYxYu9?p=preview

+0

您的格式化程序将日期值转换为字符串,那么您的解析器呢?是否需要做相反的工作(将字符串转换为日期值)? – Rustam

+0

解析器已经将相应的Date对象返回给我。 – Mik378

+0

您不能可靠地更改输入类型日期的格式。浏览器将在该字段中呈现区域设置的格式化日期。所以你的指示在这种情况下是无用的。 – dfsq

回答

-1

在这种情况下,最好使用<input type="text" />,而不是date更好的浏览器兼容性。它还可以防止Angular将值强制为Date。您仍然可以在自定义指令中使用自定义分析器和格式器。

.directive('dateToFormat', function ($filter) { 
    return { 
     restrict: 'A', 
     require: 'ngModel', 
     link: function (scope, el, attrs, ctrl) { 
      ctrl.$parsers.push(function (data) { 
       return new Date(data); // Maybe use some parsing libraries. 
      }); 
      ctrl.$formatters.push(function (data) { 
       return $filter('date')(data, 'EEE dd MMMM yyyy'); 
       // Now you can return strings as you like! 
      }); 
     } 
    }; 
}); 
+0

你将失去​​移动组件的好处,在这种情况下,需要输入日期。 https://www.google.com/search?q=ios+select+date&client=safari&rls=en&source=lnms&tbm=isch&sa=X&ved=0CAgQ_AUoAmoVChMIsue_8orlxwIVBF4aCh0D-wvt&biw=1285&bih=712#imgrc=ZfCfDQkHVlGkqM%3A – Mik378

+0

有关显示如何' 触摸屏版本,仍然使用桌面文本?然后,你可以获得两全其美的好处。 – FelisCatus

+0

这是一个移动应用程序;)离子不要打扰桌面。 – Mik378