有没有一种方法在角JS获取时间戳从表单获得的日期?AngularJs从人类可读的日期获取时间戳
<label for="start">From:</label>
<input type="date" ng-model="startDate" />
我需要在指令中编写什么来转换这些数据?我没有找到关于这个特定问题的任何信息, Regards
有没有一种方法在角JS获取时间戳从表单获得的日期?AngularJs从人类可读的日期获取时间戳
<label for="start">From:</label>
<input type="date" ng-model="startDate" />
我需要在指令中编写什么来转换这些数据?我没有找到关于这个特定问题的任何信息, Regards
使用指令将视图中的值更改为模型。
http://jsfiddle.net/bateast/Q6py9/1/
angular.module('app', [])
.directive('stringToTimestamp', function() {
return {
require: 'ngModel',
link: function(scope, ele, attr, ngModel) {
// view to model
ngModel.$parsers.push(function(value) {
return Date.parse(value);
});
}
}
});
我将如何添加“模型查看”转换? – ovi
使用ngModel。$ formatter,你可以在这里查看文档:https://docs.angularjs.org/api/ng/type/ngModel.NgModelController –
由于您使用输入类型作为日期,因此模型中的字符串应该与javascript中的Date
对象兼容。所以,你可以做
var timestamp = new Date($scope.startDate).getTime()
要在控制器使用,你可以做这样的事情:
myApp.controller('TimestampCtrl', ['$scope', function($scope) {
$scope.toTimestamp = function(date) {
var dateSplitted = date.split('-'); // date must be in DD-MM-YYYY format
var formattedDate = dateSplitted[1]+'/'+dateSplitted[0]+'/'+dateSplitted[2];
return new Date(formattedDate).getTime();
};
}]);
而且可以这样使用:
<div ng-controller="TimestampCtrl">
The timestamp of <input ng-model="date"> is {{ toTimestamp(date) }}
</div>
这不会在Safari工作。不要使用..它。 – lin
http://stackoverflow.com/questions/15718203/dealing-with-transformed-data-in-angularjs –