Custom reformat date filter
by Michael Conroy
HTML
<div ng-app="myApp"
<div ng-controller="myCtrl">
<input type="text" ng-model="myDate"> <small>Format: YYYYMMDD</small>
<p>
{{myDate | myFormatDateFilter}}
</p>
</div>
</div>
CSS
small { color: #999; }
JavaScript
angular.module('myApp',[])
.controller('myCtrl',function($scope){
$scope.myDate = '20131115';
$scope.$watch('myDate',function(val){
$scope.myDate = val.replace(/[^0-9]/gi,'');
if(val.length > 8)
$scope.myDate = val.slice(0,8);
});
})
.filter('myFormatDateFilter',function(){
return function(input){
if(angular.isDefined(input)){
if(input.length > 8)
input = input.slice(0,8);
if(input.length >= 4)
input = input.slice(0,4) + '/' + input.slice(4);
if(input.length >= 7)
input = input.slice(0,7) + '/' + input.slice(7);
}
return input;
};
});