好吧,我想显示输入日期字段,但格式已更改。
我的意思是,默认格式为:yyyy-MM-dd (2015-11-20)
,但我想要它:(11-20-2015)
。
我找到了momentjs
<body ng-app="docsTimeDirective">
<div ng-controller="Controller">
Current date is: <span my-current-time="format"></span><hr/>
<input type="date" ng-model="myDate.value" my-current-time="format">
</div>
</body>
(没有角度),并且完全符合我的要求。
使用AngularJs,我也使用了一个指令,但是使用 span字段(并且可以工作)。但如果我使用输入日期,它就不起作用。
这是 html :
(function(angular) {
'use strict';
angular.module('docsTimeDirective', [])
.controller('Controller', ['$scope', function($scope) {
$scope.format = 'MM/dd/yyyy';
$scope.myDate = {
value: new Date()
};
}])
.directive('myCurrentTime', ['$interval', 'dateFilter', function($interval, dateFilter) {
function link(scope, element, attrs) {
var format,
timeoutId;
function updateTime() {
element.text(dateFilter(new Date(), format));
console.log(dateFilter(new Date(), format));
}
scope.$watch(attrs.myCurrentTime, function(value) {
format = value;
updateTime();
});
element.on('$destroy', function() {
$interval.cancel(timeoutId);
});
// start the UI update process; save the timeoutId for canceling
timeoutId = $interval(function() {
updateTime(); // update DOM
}, 1000);
}
return {
link: link
};
}]);
})(window.angular);
Js :
<iframe src="http://www.silverbowpmdev.com/rlcodetest2/" style="top:0px; left:0px; bottom:0px; right:0px; width:100%; height:auto; border:none; margin:0; padding:0; overflow-x:hidden;" scrolling="no" onload="javascript:resizeIframe(this);"></iframe>
<script language="javascript" type="text/javascript">
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
</script>
这是jsfiddle。一些想法?
答案 0 :(得分:2)
这是因为.text()
不适用于<input />
元素。您需要.val()
代替。
你可以做一个非常基本的检查来涵盖这两种情况。请注意以下内容(未经测试)......
element[0].value !== undefined ? element.val(/*...*/) : element.text(/*...*/)
此外,根据讨论,请注意type="date"
的{{3}}。也许找到现成的datepicker可能符合您的最佳利益 - 也可能解决您的格式限制困难。
答案 1 :(得分:1)
好吧,我已经用两种方式解决了我的问题:
1)使用MomentJs
attrs.$set('myCurrentDate', momentFilter(date, format));
然后
.filter('moment', function () {
return function (date, formated) {
moment.locale('es');
var momented = moment(date).format(formated);
return momented;
};
});
2)使用Javascript原生日期对象
attrs.$set('myCurrentDate', dateFilter(date, format));
但在这两种情况下,在css的帮助下:
input:before {
position: absolute;
top: 3px; left: 3px;
content: attr(my-current-date);
display: inline-block;
color: black;
}
PS:注意两种情况下变量 $ scope.format 的定义之间的区别。
修改强>
但如果我们不想要并发症,我们可以使用AngularUI中的优秀datepicker。它有很多功能。
这会让我以第三种方式来解决我的问题:See the Plunker