Ich möchte, dass der Server das Datum ohne Änderung zurückgibt und Javascript die Ansicht massiert. Meine API gibt "MM / TT / JJJJ hh: mm: ss" von SQL Server zurück.
Ressource
angular.module('myApp').factory('myResource',
function($resource) {
return $resource('api/myRestEndpoint/', null,
{
'GET': { method: 'GET' },
'QUERY': { method: 'GET', isArray: true },
'POST': { method: 'POST' },
'PUT': { method: 'PUT' },
'DELETE': { method: 'DELETE' }
});
}
);
Regler
var getHttpJson = function () {
return myResource.GET().$promise.then(
function (response) {
if (response.myDateExample) {
response.myDateExample = $filter('date')(new Date(response.myDateExample), 'M/d/yyyy');
};
$scope.myModel= response;
},
function (response) {
console.log(response.data);
}
);
};
myDate-Validierungsrichtlinie
angular.module('myApp').directive('myDate',
function($window) {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
var moment = $window.moment;
var acceptableFormats = ['M/D/YYYY', 'M-D-YYYY'];
function isDate(value) {
var m = moment(value, acceptableFormats, true);
var isValid = m.isValid();
//console.log(value);
//console.log(isValid);
return isValid;
};
ngModel.$parsers.push(function(value) {
if (!value || value.length === 0) {
return value;
};
if (isDate(value)) {
ngModel.$setValidity('myDate', true);
} else {
ngModel.$setValidity('myDate', false);
}
return value;
});
}
}
}
);
HTML
<div class="form-group">
<label for="myDateExample">My Date Example</label>
<input id="myDateExample"
name="myDateExample"
class="form-control"
required=""
my-date
maxlength="50"
ng-model="myModel.myDateExample"
type="text" />
<div ng-messages="myForm.myDateExample.$error" ng-if="myForm.$submitted || myForm.myDateExample.$touched" class="errors">
<div ng-messages-include="template/validation/messages.html"></div>
</div>
</div>
template / validation / messages.html
<div ng-message="required">Required Field</div>
<div ng-message="number">Must be a number</div>
<div ng-message="email">Must be a valid email address</div>
<div ng-message="minlength">The data entered is too short</div>
<div ng-message="maxlength">The data entered is too long</div>
<div ng-message="myDate">Must be a valid date</div>
Date()
Funktionen:$scope.departDate = new Date(); $scope.departTime = $scope.departDate.toTimeString().slice(0, 5);
Und keine Notwendigkeit für andere Filter oder knifflige Problemumgehungen in AngularJS IMO.