本文介绍了Angularjs 手写日历的实现代码(不用插件),分享给大家,具体如下:
效果:
Html:
js:
$scope.all_month = [];
$scope.showTime = function() {
//在select中填入年份
for(var year = 2016; year < 2050; year++) {
var obj_1 = {'value': year,'id': year}
$scope.all_year.push(obj_1);
}
//在select中填入月份
for(var month = 1; month < 13; month++) {
var obj_2 = {'value': month,'id': month}
$scope.all_month.push(obj_2);
}
console.log($scope.all_year)
//初始化显示 当前年和月
$scope.show_now()
}
//当select的选中的option发送变化的触发的事件
$scope.change_year = function(data) {
$scope.showDays(data,$scope.select_month)
}
$scope.change_month = function(data) {
$scope.showDays($scope.select_year,data)
}
//返回指定的月份的天数 月份1-12
$scope.calDays = function (year,month) {
return new Date(year,month,0).getDate();
}
$scope.days = [];
//展示指定的年和月的所有日期
$scope.showDays = function(year,month) {
$scope.days = [];
//得到表示指定年和月的1日的那个时间对象
var date = new Date(year,month - 1,1);
//1.先添加响应的空白的li:这个月1号是星期几,就添加几个空白的li
var dayOfWeek = date.getDay(); //得到1日是星期几
for(var i = 0; i < dayOfWeek; i++) {
$scope.days.push("");
}
//计算一个月有多少天
var daysOfMonth = $scope.calDays(year,month);
//2. 从1号开始添加li
for(var i = 1; i <= daysOfMonth; i++) {
$scope.days.push(i)
}
}
$scope.active_day = ''
$scope.select_year = ''
$scope.select_month = ''
//初始化显示 当前年和月
$scope.show_now = function() {
var now = new Date();
// $("#time_year").val(now.getFullYear());
// $("#time_month").val(now.getMonth() + 1);
$scope.active_day = now.getDate();
$scope.select_year = now.getFullYear();
$scope.select_month = now.getMonth() + 1;
$scope.showDays($scope.select_year,$scope.select_month)
}
$scope.change_day = function(day){
$scope.active_day = ""
$scope.active_day = day
}
// 以上是创建日历