Jquery datepicker button is not working well - angularjs

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

Related

Generate Array of months with moment - Reactjs

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"
]

Show Color on Specific dates in datetime-picker AngularJs

I'm using bootstrap datetime-picker in angularjs
I need to show color on some specific dates i.e. on weekend and holiday dates
Here is my date picker option :-
$scope.dateOptions = {
dateFormat: 'yyyy-MM-dd',
maxDate: new Date(2020, 5, 22),
minDate: new Date(),
startingDay: 1,
onChangeDate: countDays
};
I'm getting list of holidays from database and weekends I'm able to identify.
How to show color to specific date?
I tried using some custom css but its applying on all the dates not to specific.
Thanks!
Answering your question
How to show color to specific date?
Bootstrap datetime-picker for Angularjs Do provide an option to apply custom class.
Try this
$scope.dateOptions = {
dateFormat: 'yyyy-MM-dd',
maxDate: new Date(2020, 5, 22),
minDate: new Date(),
startingDay: 1,
onChangeDate: countDays,
customClass: getDayClass // fucntion having logic to select particular dates
};
The function getDayClass can be implement like this
function getDayClass(data) {
var date = data.date,
mode = data.mode;
if (mode === 'day') {
var dayToCheck = new Date(date).setHours(0,0,0,0);
for (var i = 0; i < $scope.events.length; i++) {
var currentDay = new Date($scope.events[i].date).setHours(0,0,0,0);
if (dayToCheck === currentDay) {
return $scope.events[i].status;
}
}
// check for weekend 0 for sun and 6 for sat
if(date.getDay() == 0 || date.getDay() == 6)
{
return 'full'; //return class to be applied
}
}
return '';
}
Set the class for dates
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
var afterTomorrow = new Date(tomorrow);
afterTomorrow.setDate(tomorrow.getDate() + 1);
$scope.events = [
{
date: tomorrow,
status: 'full'
},
{
date: afterTomorrow,
status: 'partially'
}
];
The date picker calls date picker options for every date at the time of initialization.
you can check the Plunker example.

Angular -- ng-init scope variable not passing into view

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

Get date to display just month and year AngularJS, Firebase

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();
}

how to pass variable values to controller

<div id="dsel1" style="text-align:center;width:800px;"></div><br>
<br>
<span id="wtf"></span>
<script type="text/javascript">
var calendarPicker1 = $("#dsel1").calendarPicker({
monthNames:["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
dayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
callback:function(cal) {
var date=cal.currentDate;
alert(date);
$("#wtf").html("Selected date: " + cal.currentDate);
}});
</script>
here this code displays date from datepicker , it works fine but i have to pass the date variable value to profiles controller, index action with this one id and the date cariable
// javascript redirect
window.location = '/profiles/index?id=123&date=2014-05-03'
// ProfilesController
public function index() {
$id = $this->request->query['id'];
$date = $this->request->query['date'];
}
OR if you want to stay on the same page use ajax
$.ajax({
url:'/profiles/index',
data:{id:123, date:'2014-05-03'},
type:'POST',
success:function(data, textStatus, jqXHR) {
// do something
}
})
// ProfilesController
public function index() {
if($this->request->is('ajax')) {
$id = $this->request->data['id'];
$date = $this->request->data['date'];
// do something
}
}

Resources