我使用$http。获取一个服务来获取JSON数据。在返回的JSON中,我的对象属性之一是一个没有被AngularJS解析的日期。我需要将此属性绑定到日期字段,我目前正在通过手动将JSON字符串转换为javascript日期抓取AJAX数据后,如下所示
app.service('MainService', function(){
var self = this;
self.jsonDate = null;
self.parsedDate = null;
// this function will get JSON data from an API in production
self.getData = function(){
var jsonData = "2014-06-13T16:00:00";
// Angular does not convert my JSON data properties into dates
self.jsonDate = jsonData;
// I can work around this by forcing my dates to be parsed
self.parsedDate = moment(jsonData).toDate();
}
});
有更干净的方法吗?我构建了一个过滤器,将字符串转换为日期
app.filter('stringToDate', function () {
return function (input) {
if (!input)
return null;
var date = moment(input);
return date.isValid() ? date.toDate() : null;
};
});
滤镜效果很好,如下图所示
<span ng-bind="service.jsonDate | stringToDate | date:'MM/dd/yy'"></span>
,但它不工作,如果我试图使用它与ng-model如下所示
<input type="date" ng-model="service.jsonDate | stringToDate"/>
过滤器可以与ng-model一起使用吗?还是我需要手动将属性转换为日期?我在这里有一个柱塞,用来演示我当前的代码
http://plnkr.co/edit/pVaDbjIjtnKaYqrjAd0D?p =预览
Plunker Demo Here
有几种方法可以做到这一点:
-
使用ng-init中的过滤器初始化作用域变量,然后将ng-model绑定到作用域变量
<body ng-controller="MainCtrl" ng-init="mydate = (service.jsonDate | stringToDate)"> <label>Raw JSON Date</label> <input type="date" data-ng-model="service.jsonDate"/><br/><br/> <label>Parsed JSON date</label> <input type="date" data-ng-model="mydate"/> </body>
-
使用
$filter
服务手动调用控制器中的stringToDate
过滤器:app.controller('MainCtrl', function($scope, $filter, MainService) { $scope.service = MainService; // fetch data from service $scope.service.getData(); $scope.parsedDate = $filter('stringToDate')(MainService.jsonDate); });
然后将变量绑定到
ng-model
:<input type="date" data-ng-model="parsedDate"/>
[编辑]
-
使用一个依赖于原始JSON的ng-model的自定义指令。添加格式化程序将模型转换为日期字符串;以及将日期字符串转换回模型的解析器。这种方法的优点是可以维护双向模型绑定。当您使用有效的日期字符串更新文本框时,它会自动更新原始JSON模型(反之亦然)。
在plunker示例中,尝试输入一个有效的日期字符串,并注意模型如何自动更改。
指令:
app.directive('jsonDate', function($filter) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
//format text going to user (model to view)
ngModel.$formatters.push(function(value) {
var date = $filter('stringToDate')(value);
return date.toString();
});
//format text from the user (view to model)
ngModel.$parsers.push(function(value) {
var date = new Date(value);
if (!isNaN( date.getTime())) {
return moment(date).format();
}
});
}
}
HTML: <input type="date" data-ng-model="service.jsonDate" json-date/>
最后一个例子允许你将ngModel绑定到一个json日期字符串,并让它显示一个格式化的日期。当用户输入有效的格式化日期时,它会自动更新绑定到