我有一个Angualr服务,列出当月的12个月和一年:
JS:
app.factory('12months', function() {
return {
getMonths: function() {
var date = new Date();
var months = [],
monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
for(var i = 0; i < 12; i++) {
months.push(monthNames[date.getMonth()] + ' ' + date.getFullYear());
date.setMonth(date.getMonth() - 1);
}
return months;
}
};
});
哪个输出是:
Oct 2014, Sep 2014, Aug 2014 etc etc
我如何修改它以显示日期,所以:
21 Oct 2014, 21 Sep 2014, 21 Aug 2014 etc etc
答案 0 :(得分:3)
如何使用date filter
var app = angular.module('my-app', [], function() {
})
app.controller('AppController', ['$scope', '12months',
function($scope, tmonths) {
$scope.tmonths = tmonths.getMonths();
}
])
app.factory('12months', ['dateFilter',
function(dateFilter) {
return {
getMonths: function() {
var date = new Date();
var months = [];
for (var i = 0; i < 12; i++) {
months.push(dateFilter(date, 'dd MMM yyyy'));
date.setMonth(date.getMonth() - 1)
}
return months;
}
};
}
]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="my-app" ng-controller="AppController">
<pre>{{tmonths | json}}</pre>
</div>
&#13;
答案 1 :(得分:2)
您可以将日期连接到months数组中的字符串:
所以不要这样:
months.push(monthNames[date.getMonth()] + ' ' + date.getFullYear());
这样做:
months.push(date.getDate() + ' ' + monthNames[date.getMonth()] + ' ' + date.getFullYear());
答案 2 :(得分:2)
将日期附加到字符串:
app.factory('12months', function() {
return {
getMonths: function() {
var date = new Date();
var months = [],
monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
for(var i = 0; i < 12; i++) {
months.push(date.getDate()+ ' ' +monthNames[date.getMonth()] + ' ' + date.getFullYear());
}
return months;
}
};
});
答案 3 :(得分:1)
您可以在jquery
中约会var date = new Date();
date.getDate() //output:- 21
答案 4 :(得分:1)
添加天数中的总天数:
app.factory('twelvemonths', function() {
return {
getMonths: function() {
var date = new Date();
var months = [],
monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
days=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31];
for(var i = 0; i < 12; i++) {
months.push(days[date.getDate()]+ ' ' +monthNames[date.getMonth()] + ' ' + date.getFullYear());
}
return months;
}
};
});
答案 5 :(得分:1)
如果您想使用您的功能,可以将线路更改为
months.push(date.getDate() + ' ' monthNames[date.getMonth()] + ' ' + date.getFullYear());