Load data dynamically when I change the date - angularjs

This is my calendar object
$scope.uiConfig = {
calendar: {
height: 450,
editable: false,
header: {
left: 'title',
center: '',
right: 'today prev,next'
},
eventClick: $scope.onEventClick,
eventDrop: $scope.alertOnDrop,
eventResize: $scope.alertOnResize,
eventRender: $scope.eventRender,
dayClick: $scope.onDayClick,
viewRender: $scope.getData
}
};
and
$scope.getData = function(view, element){
$scope.intervalStartDate = new Date(view.start);
$scope.intervalEndDate = new Date(view.end);
$scope.managedEvents = Event.getFittingsForDateInterval({
intervalStartDate : convertDate($scope.intervalStartDate),
intervalEndDate : convertDate($scope.intervalEndDate)
});
$scope.managedEvents.$promise.then(function(data){
$scope.uiConfig.calendar.events = data;
});
}
if I remove
$scope.uiConfig.calendar.events = data;
no data is populating and if i include that it is refreshing and loading current month data
for the first time it is loading the data for January month, whenever I click on next month icon, it is calling for February month data and again calendar is resetting to present month (it is calling $scope.getData again)
data = [{start : some_date, end : some_date, title : event_name},{start : some_date, end : some_date, title : event_name},{start : some_date, end : some_date, title : event_name},{start : some_date, end : some_date, title : event_name},{start : some_date, end : some_date, title : event_name}];
I want to get data for only current view instead of all at once.
any help would be appreciated.

Controller.js Code: .
$scope.getEvents = function(){
var obj = {};
$scope.events = [];
obj.startDate = new Date($scope.myView.intervalStart).getTime();
obj.endDate = new Date($scope.myView.intervalEnd).getTime();
if($scope.myView.name == "month"){
obj.endDate = obj.endDate - 19801000;
}
//Give a call to database from here, in which obj contains
// start and end of the view
var getEventsPromise = masterCalendarAPI.getEvents(obj);
getEventsPromise.then(function (response) {
if(response.statusCode == 200){
//Assign $scope.event the list object retrieved from database
}
},
function (error) {
console.log(error);
});
}
//Remember this method will be called on each view change with all details in 'view' object
$scope.renderView = function (view) {
$scope.myView = view;
$scope.getEvents();
}
$scope.uiConfig = {
calendar: {
height: 500,
editable: false,
header: {
left: 'prev,next title',
center: '',
right: 'month,agendaWeek,agendaDay'
},
eventLimit: true,
views: {
month: {
eventLimit:3
}
},
columnFormat:'dddd',
timezone: 'local',
timeFormat: 'hh:mm a',
titleFormat:'MMMM D, YYYY',
slotDuration:'00:30:00',
eventRender:$scope.eventRender,
eventClick: $scope.eventClicked,
dayClick: $scope.dayClick,
eventDrop: $scope.alertOnDrop,
eventResize: $scope.alertOnResize,
viewRender: $scope.renderView
}
} ;
//event sources array
$scope.eventSources = [$scope.events];

Related

How to update event source object to particular event source in full calendar dynamically

Hello I have loaded one calendar using below code.
dataFactory.httpRequest('getCalanderTaskData','GET').then(function(data) {
$scope.taskCalanderDailyTask = data.dailyTask;
$scope.taskCalanderDueTask = data.dueTask;
$scope.fullCalendarEventSources = {
dailyTask : {
events:$scope.taskCalanderDailyTask,
textColor : '#000',
backgroundColor: '#FFD000',
},
dueTask : {
events:$scope.taskCalanderDueTask,
textColor : '#fff',
backgroundColor: '#da1445',
}
};
$('#fullcalendar').fullCalendar({
eventClick: function(calEvent, jsEvent, view) {
},
eventMouseover: function(calEvent, jsEvent, view) {
var tooltip = '<div class="tooltipevent" style="color:#fff;width:100px;height:50px;background:#125688;position:absolute;z-index:10001;">' + calEvent.title + '</div>';
var $tooltip = $(tooltip).appendTo('body');
$(this).mouseover(function(e) {
$(this).css('z-index', 10000);
$tooltip.fadeIn('500');
$tooltip.fadeTo('10', 1.9);
}).mousemove(function(e) {
$tooltip.css('top', e.pageY + 10);
$tooltip.css('left', e.pageX + 20);
});
},
eventMouseout: function(calEvent, jsEvent) {
$(this).css('z-index', 8);
$('.tooltipevent').remove();
},
eventLimit: 3,
eventSources: [$scope.fullCalendarEventSources.dailyTask, $scope.fullCalendarEventSources.dueTask],
});
});
Above code load first time calendar now when any new task going to added I want to refresh calendar event source without reload page.
Below is the code for saveTask Inside that I have written code for dynamic event source which also remove source and added source but it not update newly added tasks.
$scope.saveTask = function(){
$scope.form.taskLeadId = $scope.leadId;
$scope.form.taskId = $scope.editTaskId;
if($scope.form.taskLeadId != "undefined" && $scope.form.taskLeadId != "")
{
dataFactory.httpRequest('taskCreate','POST',{},$scope.form).then(function(data) {
if(data.status == 1)
{
alertify.notify(data.message, 'success', 5, function(){});
$scope.addTask.$setPristine();
$scope.addTask.$setUntouched();
$scope.form = {};
$(".modal").modal("hide");
getDailyTaskData();
getCalanderTaskData();
console.log("updateed=="+$scope.taskCalanderDailyTask);
$scope.fullCalendarEventSources = {
dailyTask : {
events:$scope.taskCalanderDailyTask,
textColor : '#000',
backgroundColor: '#FFD000',
},
dueTask : {
events:$scope.taskCalanderDueTask,
textColor : '#fff',
backgroundColor: '#da1445',
}
};
$timeout(function () {
$('#fullcalendar').fullCalendar('removeEventSource',$scope.fullCalendarEventSources.dailyTask);
console.log("updateed=="+$scope.taskCalanderDailyTask);
$('#fullcalendar').fullCalendar('addEventSource',$scope.fullCalendarEventSources.dailyTask);
$('#fullcalendar').fullCalendar('refetchEventSources',$scope.fullCalendarEventSources.dailyTask);
$('#fullcalendar').fullCalendar('rerenderEvents');
$('#fullcalendar').fullCalendar('refetchEvents');
$('#fullcalendar').fullCalendar('refresh');
$('#fullcalendar').fullCalendar('updateEvents',$scope.fullCalendarEventSources.dailyTask);
$('#fullcalendar').fullCalendar('rerenderEvents');
$('#fullcalendar').fullCalendar('refetchEvents');
$('#fullcalendar').fullCalendar('refresh');
console.log("after update==");
});
//alertify.alert('Task', 'Congratulations your task is created successfully!');
}
else
{
if($scope.editTask = "edit")
{
alertify.alert('Task Update','Nothing is updated');
}
else
{
alertify.alert('Error', data.message,function(){ alertify.error(data.message)});
$(".modal").modal("hide");
}
}
});
}
else
{
alertify.alert('Error', 'There must be something went wrong please try again later');
$(".modal").modal("hide");
}
}
Any one please help on this.

Calendar with only month and year in pickadate js api

Am trying with pickadate datepicker calendar in my application, is that possible to display the calendar with only month and year?
$('#datePicker').pickadate({
selectMonths: true, // Creates a dropdown to control month
selectYears: 150, // Creates a dropdown of 15 years to control year
format: 'mmm-yyyy',
max: true,
onSet: function (arg) {
if ('select' in arg) { //prevent closing on selecting month/year
this.close();
}
}
});
var from_$input = $('.from_date').pickadate({
today: 'Ok',
format: 'mmmm-yyyy',
min: new Date(),
formatSubmit: 'yyyy-mm-dd',
hiddenPrefix: 'prefix__',
hiddenSuffix: '__suffix',
selectYears: true,
selectMonths: true,
}),
var nowTemp = new Date();
var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), 0, 0, 0, 0, 0);
var checkin = $('#dpd1').datepicker({
onRender: function(date) {
return date.valueOf() < now.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function(ev) {
if (ev.date.valueOf() > checkout.date.valueOf()) {
var newDate = new Date(ev.date)
newDate.setDate(newDate.getDate() + 1);
checkout.setValue(newDate);
}
checkin.hide();
$('#dpd2')[0].focus();
}).data('datepicker');
var checkout = $('#dpd2').datepicker({
onRender: function(date) {
return date.valueOf() <= checkin.date.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function(ev) {
checkout.hide();
}).data('datepicker');

Updating highcharts dynamically with json response

I am trying to draw highcharts with the json response, however I can able to draw for the first time, but unable to update the series with new data
function get_chart(data) {
//alert('hello..' + data);
return {
xAxis: {
type: 'datetime',
labels: {
formatter: function() {
var monthStr = Highcharts.dateFormat('%b', this.value);
var firstLetter = monthStr.substring(0, 1);
return firstLetter;
}
}
},
title: {
text: data.measurementName
},
chart: {
height: 300,
width: 500,
type: 'column',
zoomType: 'x'
},
credits: {
enabled: false
},
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function() {
console.log ('Category: '+ this.category +', value: '+ this.y);
}
}
}
}
},
series: [{
name: 'Hours',
data: (function() {
var chart = [{key:data.measurementName, values:[]}];
var i = 0;
if(typeof(data) == 'string')return chart;
for(n in data.values){
data.values[n].snapshot = new Date(data.values[n].snapshot);
data.values[n].value = parseInt(data.values[n].value);
}
chart[0].values = data.values.map(function(arrayObj){
return [arrayObj.value]
});
return chart[0].values;
})()
}]
};
}
and I am calling this function like
$scope.renderChart = function(measurement){
$scope.showChart = false;
restApp.getMeasurementForCompID(comp.id, measurement.id).then(function(data){
console.log(data);
$scope.example_chart = get_chart(data);
console.log($scope.example_chart);
$scope.showChart = true;
});
}
Here getMeasurementForCompID is another function which gets the data from database.
What is the problem here? any help..
I used https://github.com/pablojim/highcharts-ng
I just alter the data object and the highcharts reflects the change.

Rally App SDK getting object ID of feature

var showAssignedProgram = 1;
var value = null;
var showIterationCombo = 0;
var iterationComboValue = null;
var lumenize = window.parent.Rally.data.lookback.Lumenize;
var iterationComboField = null;
var iterationRecord = myMask = null;
var setOfStories = setOfFeatures = null;
Ext.define('CustomApp', {
extend: 'Rally.app.App',
componentCls: 'app',
launch: function() {
//Write app code here
Ext.state.Manager.setProvider(
new Ext.state.CookieProvider({ expires: new Date(new Date().getTime()+(10006060247)) })
);
app = this;
var that = this;
console.log("launch");
// get the project id.
this.project = this.getContext().getProject().ObjectID;
// get the release (if on a page scoped to the release)
var tbName = getReleaseTimeBox(this);
var configs = [];
configs.push({ model : "Release",
fetch : ['Name', 'ObjectID', 'Project', 'ReleaseStartDate', 'ReleaseDate' ],
filters:[]
});
configs.push({ model : "Iteration",
fetch : ['Name', 'ObjectID', 'Project', 'StartDate', 'EndDate' ],
filters:[]
});
async.map( configs, this.wsapiQuery, function(err,results) {
that.releases = results[0];
that.iterations = results[1];
if (showAssignedProgram)
that.createAssignedProgramCombo();
that.createIterationCombo(that.iterations);
});
},
wsapiQuery : function( config , callback ) {
Ext.create('Rally.data.WsapiDataStore', {
autoLoad : true,
limit : "Infinity",
model : config.model,
fetch : config.fetch,
filters : config.filters,
listeners : {
scope : this,
load : function(store, data) {
callback(null,data);
}
}
});
},
createAssignedProgramCombo : function() {
// assigned Program (if set to true)
this.assignedProgramCombo = Ext.create("Rally.ui.combobox.FieldValueComboBox", {
model : "PortfolioItem/Feature",
field : "AssignedProgram",
stateful : true,
stateId : "assignedProgramCombo",
noData: false,
listeners:{
scope: this,
change: function(field,eOpts){
if(value!="" && value!=null)
{
this.afterCollapse(fieldValue,value);
}
}
}
});
this.add(this.assignedProgramCombo);
},
createIterationCombo: function(iterationRecords){
//console.log("Iteration records ",iterationRecords);
iterationRecord = iterationRecords;
var iterations = _.map(iterationRecords, function(rec){return {name: rec.get("Name"), objectid: rec.get("ObjectID"), startDate: new Date(Date.parse(rec.get("StartDate")))};});
console.log('iterations', iterations);
iterations = _.uniq(iterations, function(r){return r.name;});
iterations = _.sortBy(iterations, function(rec){return rec.StartDate;}).reverse();
var iterationStore = Ext.create('Ext.data.Store', {
fields: ['name','objectid'], data : iterations
});
var cb = Ext.create('Ext.form.ComboBox',{
fieldLabel: 'Iterations',
store: iterationStore,
queryMode: 'local',
displayField: 'name',
valueField: 'name',
listeners:{
scope: this,
change: function(field, eOpts){
console.log('field ', field, ' eOpts ',eOpts);
iterationComboValue = eOpts;
iterationComboField = field;
},
collapse: function(field, eOpts){
this.afterCollapse(field,eOpts);
}
}
});
this.add(cb);
},
afterCollapse: function(field,eOpts){
var r = [];
_.each(field.getValue().split(","), function(rn){
var matching_iterations = _.filter(iterationRecord, function(r){return rn == r.get("Name");});
var uniq_iterations = _.uniq(matching_iterations, function(r){return r.get("Name");});
_.each(uniq_iterations,function(iteration){r.push(iteration);});
});
if(r.length>0){
myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
myMask.show();
this.selectedIterations = r;
this.queryFeatures(r);
}
},
queryFeatures: function(iterations){
var that = this;
var filter = null;
if (showAssignedProgram && this.assignedProgramCombo.getValue() != null && this.assignedProgramCombo.getValue() != "") {
console.log("assingedValue",this.assignedProgramCombo.getValue());
filter = Ext.create('Rally.data.QueryFilter', {
property: 'AssignedProgram',
operator: '=',
value: this.assignedProgramCombo.getValue()
});
}
else{
_.each(iterations, function(iteration, i){
var f = Ext.create('Rally.data.QueryFilter', {
property: 'Iteration.Name',
operator: '=',
value: iteration.get("Name")
});
filter = i === 0 ? f : filter.or(f);
});
}
console.log("filter",filter.toString());
var configs = [];
configs.push({
model: 'PortfolioItem/Feature',
fetch: ['ObjectID','FormattedID','UserStories' ],
filters: [filter],
listeners: {
load: function(store, features) {
setOfFeatures = features;
console.log("# features",features.length,features);
that.StartDate = that.startDate(iterations);
that.start = _.min(_.pluck(iterations,function(r) { return r.get("StartDate");}));
isoStart = new lumenize.Time(that.start).getISOStringInTZ("America/Chicago");
console.log("isoStart1",isoStart);
that.end = _.max(_.pluck(iterations,function(r) { return r.get("EndDate");}));
that.iterations = iterations;
console.log('End date ',that.end);
// that.getStorySnapshotsForFeatures( features, iterations);
}
}
});
configs.push({
model: 'HierarchicalRequirement',
limit: 'Infinity',
fetch: ['Name','Iteration','ObjectID','Feature'],
filters: [{
property: 'Iteration.Name',
operator: '=',
value: iterationComboValue
}],
listeners: {
load: function(store, stories){
setOfStories = stories;
console.log('Iteration combo value is ', iterationComboValue);
console.log("# stories ",stories.length,stories);
}
}
});
async.map(configs, this.wsapiQuery, function(err,results){
setOfFeatures = results[0];
console.log("# features",setOfFeatures.length,setOfFeatures);
that.StartDate = that.startDate(iterations);
that.start = _.min(_.pluck(iterations,function(r) { return r.get("StartDate");}));
isoStart = new lumenize.Time(that.start).getISOStringInTZ("America/Chicago");
that.end = _.max(_.pluck(iterations,function(r) { return r.get("EndDate");}));
that.iterations = iterations;
//Here is the problem
setOfStories = results[1];
var stories = _.map(setOfStories, function(story){ return {name: story.get("Name"),fid: story.get("Feature").ObjectID,objectid: story.get("ObjectID")};}); //throws error
console.log('stories ',setOfStories);
var features = _.map(setOfFeatures, function(feature){return {name: feature.get("Name"), fid: feature.get("ObjectID")};});
console.log('features ',setOfFeatures);
var candidateStories = [];
_.each(stories, function(story){_.each(features, function(feature){
if(story.fid == feature){
candidateStories.push(story);
}
});});
console.log('candidate stories ',candidateStories.length,candidateStories);
if(candidateStories!=null){
that.getStorySnapShotsForFeatures(candidateStories);
}
//create snapshot store based on candidateStories.
});
},
getStorySnapShotsForFeatures: function(stories){
var snapshots = [];
var that = this;
async.map(stories, this.readStorySnapshots,function(err,results){
console.log('results ',results);
});
},
readStorySnapshots: function(parent,callback){
console.log('inside story snapshots ');
Ext.create('Rally.data.lookback.SnapshotStore',{
limit: 'Infinity',
autoLoad: true,
listeners:{
scope: this,
load: function(store,data,success){
callback(null,data);
}
},
fetch: ['ObjectID'],
filters:[{
property: 'ObjectID',
operator: 'in',
value: ['ObjectID']
},
{
property: '__At',
operator: '=',
value: 'current'
}]
});
},
startDate: function(iterations){
var start = _.min(_.pluck(iterations, function(r){return r.get("StartDate");}));
return Rally.util.DateTime.toIsoString(start, false);
}
});
In the async.map callback function, when setOfStories are returned, I try to map the name, fid, and objectID to a new array. But for some reason, the fid: story.get("Feature").ObjectID gives an error saying get("") is null. But just before returning the array, when I console log story.get("Feature").ObjectID the correct value is printed, but somehow when I try to return the same value, it generates an error.
The field on HierarchicalRequirement for its PI parent is called PortfolioItem (since the PI types are customizable- feature just happens to be the default name of the lowest level one).
story.get('PortfolioItem').ObjectID

Export google chart?

I wrote this code to create chart, table and toolbar.
google.load("visualization", "1", { packages: ["corechart"] });
google.load('visualization', '1', { packages: ['table'] });
//google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "GET",
url: '#Url.Action("GunlukOkumalar", "Enerji")',
data: "startDate=" + $('#start_date').val() + "&endDate=" + $('#end_date').val() + "&sayac_id=" + $("#sayaclar").val(), //belirli aralıklardaki veriyi cekmek için
success: function (result) {
if (result.success) {
var evalledData = eval("(" + result.chartData + ")");
var opts = { curveType: "function", width: '100%', height: 500, pointSize: 5 };
new google.visualization.LineChart($("#chart_div").get(0)).draw(new google.visualization.DataTable(evalledData, 0.5), opts);
$('#chart_div').show();
var visualization;
var data;
var options = { 'showRowNumber': true };
data = new google.visualization.DataTable(evalledData, 0.5);
// Set paging configuration options
// Note: these options are changed by the UI controls in the example.
options['page'] = 'enable';
options['pageSize'] = 10;
options['pagingSymbols'] = { prev: 'prev', next: 'next' };
options['pagingButtonsConfiguration'] = 'auto';
// Create and draw the visualization.
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, options);
var components = [
{ type: 'html', datasource: data },
{ type: 'csv', datasource: data }
];
var container = document.getElementById('toolbar_div');
google.visualization.drawToolbar(container, components);
return false;
}
else {
$('#chart_div').html('<span style="color:red;"><b>' + result.Error + '</b></span>');
$('#chart_div').show();
$('#table').html('<span style="color:red;"><b>' + result.Error + '</b></span>');
$('#table').show();
return false;
}
}
});
}
Google example
function drawToolbar() {
var components = [
{type: 'igoogle', datasource: 'https://spreadsheets.google.com/tq?key=pCQbetd-CptHnwJEfo8tALA',
gadget: 'https://www.google.com/ig/modules/pie-chart.xml',
userprefs: {'3d': 1}},
{type: 'html', datasource: 'https://spreadsheets.google.com/tq?key=pCQbetd-CptHnwJEfo8tALA'},
{type: 'csv', datasource: 'https://spreadsheets.google.com/tq?key=pCQbetd-CptHnwJEfo8tALA'},
{type: 'htmlcode', datasource: 'https://spreadsheets.google.com/tq?key=pCQbetd-CptHnwJEfo8tALA',
gadget: 'https://www.google.com/ig/modules/pie-chart.xml',
userprefs: {'3d': 1},
style: 'width: 800px; height: 700px; border: 3px solid purple;'}
];
var container = document.getElementById('toolbar_div');
google.visualization.drawToolbar(container, components);
};
Google get dataSource from url, but I get dataSource dynamicly from controller. When I try to export It forwards page to another page like this:
http://localhost:49972/Enerji/%5Bobject%20Object%5D?tqx=out%3Acsv%3B
How can I use exporting toolbar for dynamic Json data? Is there any example about this topic?
I also had this problem and after a lot of trawling I found this!
https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
I haven't implemented it yet but I reckon it's the way to go.

Resources