I have the following in my index.html
<header>
<select ng-model="date.month" ng-init="currentMonth" ng-options="month for month in months">
</select>
<select ng-model="date.year" ng-init="date.year" ng-options="year for year in years">
</select>
</header>
I have the following in my app.js
.controller('MainCtrl', function ($scope) {
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth();
$scope.date = {
year: year,
month: month
};
$scope.months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
$scope.currentMonth = $scope.months[month - 1];
var years = [];
var earliestYear = year - 100;
for (var i = earliestYear; i <= year; i++) {
years.push(i);
}
$scope.years = years;
$scope.$watchCollection('date', function (date) {
$scope.currentDate = new Date(date.year, date.month, 1);
});
My ng-init for "date.year" works, but not for "currentMonth". However, I know currentMonth is connected to the view. Why isn't ng-init recognizing ng-init="currentMonth"?
ng-init is an expression so you need to assign currentMonth to your date.month model.
<select ng-model="date.month" ng-init="date.month=currentMonth" ng-options="month for month in months">
</select>
The ng-init="date.year" doesn't actually do anything. The date.year model has already been assigned 2016 so it looks like it works.
See plunker
Related
I am using ant design select field with options of months. I have an array of 12 months of a year and I am mapping it through and displaying it as dropdown selectable options. I want to disable all previous months before present month. For example, If present month is October, I want to disable all of previous months before October, so user won't be able to select those months. This is how it looks like on screen and below is my code, any help would be greatly appreciated.
const monthData = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];
<Select
getPopupContainer={(trigger) => return trigger}}
autoClearSearchValue={true}
bordered={false}
showSearch
placeholder="Select Month"
optionFilterProp="children"
>
{monthData.map((month) => (<Option value={month} {/*disabled = {}*/}>{month}</Option>))}
</Select>
First get the index of current month using built-in Date:
const currentMonthIndex = new Date().getMonth();
Now you can enable/disable the Option components using map:
{monthData.map((month, index) => (<Option value={month} disabled={index < currentMonthIndex}>{month}</Option>))}
My goal is to generate an array of months from today date month to 1 year in the past. So it will look like this
(based on today date 04-05-2022)
const months = ['Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May']
My current try to generate my array :
useEffect(() => {
const months = []
const dateStart = moment()
const dateEnd = moment().subtract(11, 'month')
while (dateEnd.diff(dateStart, 'months') >= 0) {
months.push(dateStart.format('MMM'))
dateStart.add(1, 'month')
}
console.log(months)
return months
},[])
Normally i think it has to be ok , but in my output i get an empty Array . Does somebody know what am i doing wrong ? Thanks for the help.
Instead off using diff(), why not use isBefore()
Also, you're adding 1 month to dateStart but that needs to be dateEnd
const months = []
const dateStart = moment()
const dateEnd = moment().subtract(11, 'month')
while (dateEnd.isBefore(dateStart, 'day')) {
months.push(dateEnd.format('MMM'))
dateEnd.add(1, 'month')
}
months.push(dateEnd.format('MMM'))
console.log(months);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>
[
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
"Jan",
"Feb",
"Mar",
"Apr",
"May"
]
I am using datepicker for my view. I also use angularjs. The problem is that when i use ok button it doesnt not change ng-model state. it still shows ng-empty. I use this value to calculate for another field, you can ignore that.
Just tell how can imake ok button active instead of onClose? I need to make sure the ng-model change when user select a month and year.
My date picker:
$(function () {
$('.date-picker').datepicker({
yearRange: "-5:+0",
showButtonPanel: true,
dateFormat: 'MM yy',
changeMonth: true,
changeYear: true,
closeText: 'OK',
beforeShow: function () {
$(this).datepicker('widget').addClass('hide-calendar');
if ((selDate = $(this).val()).length > 0) {
iYear = selDate.substring(selDate.length - 4, selDate.length);
iMonth = jQuery.inArray(selDate.substring(0, selDate.length - 5), $(this).datepicker('option', 'monthNames'));
$(this).datepicker('option', 'defaultDate', new Date(iYear, iMonth, 1));
$(this).datepicker('setDate', new Date(iYear, iMonth, 1));
}
},
onClose: function (dateText, inst) {
$(this).datepicker('widget').removeClass('hide-calendar');
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1));
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var mN = $("#monthNo").val();
if (mN == '') {
return;
}
var tm = parseInt(month) + parseInt(mN-1)
if (tm > 11) {
tm = tm - 12;
year =parseInt(year) + 1;
}
$("#to").val(monthNames[parseInt(tm)] + " " + year);
}
}).click(function () {
$('.ui-datepicker-calendar').hide();
}).attr("readonly", true);
});
$scope.$apply() is redundant. try $scope.$digest(). but remember jquery plugins always have lots of problems in angular/ try to use angular plugins/ it save you a lot of time in the future
I'm new to angular js and moment.js i have the following code which gives the start day and end day of a week like January 17th-January 23rd. but i want all the 7 days in this format january 17, monday.
My code
var currentDate,
weekStart,
weekEnd,
shortWeekFormat = 'MMMM Do';
function setCurrentDate(aMoment){
currentDate = aMoment,
weekStart = currentDate.clone().startOf('week'),
weekEnd = currentDate.clone().endOf('week')
}
setCurrentDate(moment());
$scope.currentWeek = function(){ return currentDate.format(shortWeekFormat); };
$scope.currentWeekStart = function(){ return weekStart.format(shortWeekFormat); };
$scope.currentWeekEnd = function(){ return weekEnd.format(shortWeekFormat); };
HTML
<h2><i class="fa fa-arrow-left"></i>Week Of {{currentWeek()}}{{currentWeekStart()}}-{{currentWeekEnd()}}<i class="fa fa-arrow-right"></i></h2>
<button ng-click="prevWeek()">previous week</button>
<button ng-click="nextWeek()">next week</button>
The format you want can be achieved with below moment code.
moment('01/19/2016').format("MMMM Do,dddd");
Now, to get all dates between a week you need to use array which holds all the seven dates for you. With simple for loop adding days to start date you can achieve what you want. Take a look at below sample code.
var currentDate = moment();
var weekStart = currentDate.clone().startOf('week');
var weekEnd = currentDate.clone().endOf('week');
var days = [];
for (i = 0; i <= 6; i++) {
days.push(moment(weekStart).add(i, 'days').format("MMMM Do,dddd"));
};
console.log(days);
console.log(moment('01/19/2016').format("MMMM Do,dddd"));
Now to use it with angular you can assign days array to some scope variable and use ng-repeat to display dates.
JSFiddle
Improving J-D's answer. This will return an array of moment objects:
const getCurrentWeekDays = () => {
const weekStart = moment().startOf('week');
const days = [];
for (let i = 0; i <= 6; i++) {
days.push(moment(weekStart).add(i, 'days'));
}
return days;
}
I'm confused about how to get a date to display just a month and year using angularJS and Firebase.
I have converted a date to a string to be saved in Firebase.
Let me clarify that the date that is saved is not the current date, and is not supposed to represent the creation date of the post. It is a date that is chosen with a date picker (It is supposed to represent a past completion date of a project).
This is how the date is saved in firebase:
It is a string saved as Mon Jan 25 2016 00:00:00 GMT-0500 (EST)
Here is how it is displayed in the browser. This is just one "article" of many:
I'm trying to get it to display as just "January 2016"
I'm not sure how to get it back to a date instead of a string, and then filter it so it is just the month and the year.
Here is the relevant HTML:
<body ng-controller="WelcomeCtrl">
<div class="list-group" ng-repeat="article in articles">
<a href="#" onclick="return false;" class="list-group-item active">
<h4 class="list-group-item-heading">{{article.title}}</h4>
<p class="list-group-item-text">Completed: {{article.date}}</p>
<p class="list-group-item-text"><em>{{article.tech}}</em></p>
<p class="list-group-item-text">{{article.post}}</p>
<span class="pull-right">
<button class="btn btn-xs btn-info" ng-click="editPost(article.$id, article.date)" data-target="#editModal">EDIT</button>
<button class="btn btn-xs btn-warning" ng-click="confirmDelete(article.$id)" data-target="#deleteModal" >DELETE</button>
</span>
</a>
</div>
</body>
Here is my WelcomeCtrl controller:
.controller('WelcomeCtrl', ['$scope', '$firebase', 'CommonProp', function ($scope, $firebase, CommonProp) {
$scope.username = CommonProp.getUser();
var firebaseObj = new Firebase("https://xxxxxxxx.firebaseio.com/articles");
var sync = $firebase(firebaseObj);
$scope.articles = sync.$asArray();
//I AM ASSUMING SOMETHING HAS TO GO RIGHT HERE TO CONVERT THE DATE TO A DATE OBJECT, BUT I AM NOT SURE WHAT.
//article.date = new Date(article.date); does not work.
//articles.date = new Date(articles.date); does not work.
$scope.editPost = function (id, date) {
console.log(id);
console.log(date);
var firebaseObj = new Firebase("https://xxxxxxx.firebaseio.com/articles/" + id);
var syn = $firebase(firebaseObj);
$scope.postToUpdate = syn.$asObject();
$scope.postToUpdate.date = new Date(date);
$('#editModal').modal();
};
$scope.update = function () {
console.log($scope.postToUpdate.$id);
var fb = new Firebase("https://xxxxxxxx.firebaseio.com/articles/" + $scope.postToUpdate.$id);
var article = $firebase(fb);
article.$update({
title: $scope.postToUpdate.title,
tech: $scope.postToUpdate.tech,
date: $scope.postToUpdate.date.toString(),
post: $scope.postToUpdate.post,
emailId: $scope.postToUpdate.emailId
}).then(function (ref) {
console.log(ref.key()); // bar
$('#editModal').modal('hide');
}, function (error) {
console.log("Error:", error);
});
};
$scope.confirmDelete = function (id) {
var fb = new Firebase("https://xxxxxxxx.firebaseio.com/articles/" + id);
var article = $firebase(fb);
$scope.postToDelete = article.$asObject();
$('#deleteModal').modal();
};
$scope.deletePost = function () {
var fb = new Firebase("https://xxxxxxxx.firebaseio.com/articles/" + $scope.postToDelete.$id);
var article = $firebase(fb);
article.$remove().then(function (ref) {
$('#deleteModal').modal('hide');
}, function (error) {
console.log("Error:", error);
});
};
}]);
You can parse the string representing the date to get the number of milisconds from Jan the 1st, 1970. Then use it to create a date object, from which you can extract the number of the month (from 0 to 11) and the year.
var months= ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var milis = Date.parse("Mon Jan 25 2016 00:00:00 GMT-0500 (EST)");
var d = new Date(milis)
console.log(months[d.getMonth()] + " " + d.getFullYear());
will display "January 2016"
So in your code it should look like this if I'm correct:
var months= ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
for(var i=0; i<$scope.articles.length;i++) {
var milis = Date.parse($scope.articles[i].date);
var d = new Date(milis)
$scope.articles[i].date = months[d.getMonth()] + " " + d.getFullYear();
}