Kendo Scheduler Dynamic DataSource with Angular - angularjs

I have a Kendo Scheduler on my page.
<div kendo-scheduler k-options="schedulerOptions" k-data-source="items"></div>
My angular controller will make a call to the server to get data, it looks like this, but I do not know what my URL parameter will be until it loads up ($scope.$watch).
$scope.$watch(function () { return MyService.leadID; }, function (newValue) {
if (newValue) {
getAppointmentsTabData(newValue);
}
});
var getAppointmentsTabData = function (leadID) {
MyService.getAppointmentsTabData(leadID)
.then(function (data) {
$scope.items = data;
}
}
);
};
How can I bind this data to my Kendo Scheduler?
I can get this Scheduler to work with static data, but not the JSON list of objects that get returned when the server sends them. I would like to be able to bind my $scope.items to the dataSource, but that does not appear to work.
Here is the schedulerOptions code.
$scope.schedulerOptions = {
date: new Date("2014/10/13"),
startTime: new Date("2014/10/13 07:00 AM"),
height: 310,
views: [
"agenda",
{ type: "week", selected: true, allDaySlot: false },
{ selectedDateFormat: "{0:dd-MM-yyyy}" }
],
eventTemplate: "<span class='custom-event'>{{dataItem.title}}</span>",
allDayEventTemplate: "<div class='custom-all-day-event'>{{dataItem.title}}</div>",
timezone: "Etc/UTC",
dataSource: {
data: $scope.items,
schema: {
model: {
id: "id",
fields: {
id: { from: "ID", type: "number" },
appointmentId: { from: "AppointmentId", type: "number" },
resource: { from: "Resource", type: "number" },
description: { from: "Description" },
isAllDay: { type: "boolean", from: "IsAllDay" },
end: { from: "End", type: "date" },
start: { from: "Start", type: "date" },
title: { from: "Title", defaultValue: "No title" },
startTimezone: { from: "StartTimezone" },
endTimezone: { from: "EndTimezone" },
recurrenceRule: { from: "RecurrenceRule" },
recurrenceException: { from: "RecurrenceException" },
}
}
},
}
};
I can get the static approach to work. I cannot really use the remote data approach that looks like this (below) because I do not know what my URL is until my $scope.$watch is triggered. I need to append query string params.
dataSource: {
batch: true,
transport: {
read: {
url: "/MyController/GetMyData",
dataType: "json",
},
Does anyone have any suggestions on how I can populate my Scheduler dataSource dynamically?
I have seen this question, Kendo update scheduler options dynamically, but I am not having any luck getting the setOptions(). If only I could call $scope.myScheduler.setOptions("dataSource", myJsonObjectArry), that would be awesome, but nothing.
I am able to manipulate $scope.myScheduler._data (as an array), but I need some form of a refresh method to redraw my UI. This approach doesn't seem right though.
Thanks for any help.

I am answering my own question. In case you run into this situation, here is how I solved it.
Here is my schedulerOptions now. Notice there is no dataSource set and no schema. This is because I will populate that with my own dataSource dynamically.
$scope.schedulerOptions = {
date: new Date("2014/10/13"),
startTime: new Date("2014/10/13 07:00 AM"),
showWorkHours: true,
height: 310,
views: [
"agenda",
{ type: "week", selected: true, allDaySlot: false },
{ selectedDateFormat: "{0:dd-MM-yyyy}" }
],
edit: $scope.edit,
editable: {
template: $("#editor").html()
},
timezone: "Etc/UTC",
dataSource: {
data: [], // will be set dynamically
}
};
When my data is returned to this js controller, I will call this.
$scope.myScheduler.dataSource.data(getSchedulerEvents($scope.data.items));
Which in turn will call this, which creates the dataSource for me.
var getSchedulerEvents = function (items) {
var result = [];
var event;
for (var i = 0, length = items.length; i < length; i++) {
event = items[i];
result.push(new kendo.data.SchedulerEvent({
id: event.ID,
title: event.Title,
description: event.Description,
start: kendo.parseDate(event.Start),
end: kendo.parseDate(event.End),
isAllDay: event.IsAllDay,
recurrenceException: event.RecurrenceException,
recurrenceId: event.RecurrenceId,
recurrenceRule: event.RecurrenceRule,
resource: event.Resource,
}));
}
return result;
}
If you run into this problem, hopefully this helps.

Related

typeahead only shows remote results when a similar local array is set

I have everything set correctly as far as the displayKey and the results do show up when I have a local array present but not otherwise...
componentDidMount () {
this.placeInput = document.getElementById('place-input')
this.bloodhound = new Bloodhound({
name: "xxxxx",
datumTokenizer: (d) => {
return Bloodhound.tokenizers.whitespace(d.name);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: 'http://api.geonames.org/searchJSON?username=xxxxx&featureClass=P&maxRows=5&name_startsWith=%QUERY'
},
//only seems to show results when this is present and those results have to be similar to 'California'
// local: {
// name: 'California',
// title: 'California'
// },
remote: {
url: "http://api.geonames.org/searchJSON?username=xxxxxx&featureClass=P&maxRows=5&name_startsWith=%QUERY",
wildcard: '%QUERY',
},
limit: 10
});
this.bloodhound.initialize()
$('#place-input').typeahead({
hint: true,
highlight: true,
minLength: 2
},
{
displayKey: 'name',
source: this.bloodhound.ttAdapter()
}).on('typeahead:selected', function(obj, datum) {
console.log(datum)
}.bind(this)); // END Instantiate the Typeahead UI
}
Should show remote results without local array set

KendoUI Grid for AngularJS binding error from asp.net mvc controller. Success is not a function error

I attempt to do simple task using KendoUI grid for AngularJS in asp.new mvc application. It is binding data to grid from mvc controller.
asp.net mvc controller method:
public ActionResult GetCdcReport()
{
var testJson =
#"{ProductID:'1',ProductName:'Chai',UnitPrice:'18',UnitsInStock:'39',Discontinued:'false'}";
var json = JObject.Parse(testJson);
return new JSONNetResult(json);
}
angularjs service function:
function getImportResultReport() {
return httpPost('getCdcReport');
}
code from component for data binding:
$scope.mainGridOptions = {
columns: [
{ field: "ProductID", title: "ID" },
{ field: "ProductName", title: "Product Name" },
{ command: [{ template: "<button class='k-button' ng-click='showDetails(dataItem)'>Show details</button>" }] },
],
pageable: true,
dataSource: {
pageSize: 5,
transport: {
read: function (e) {
dataservice.getImportResultReport().
success(function (data) {
e.success(data);
}).
error(function (data, status) {
alert('something went wrong');
console.log(status);
});
}
}
}
};
I see that server method is called but in console i get following client error:
dataservice.getImportResultReport(...).success is not a function
In similar question i read that:
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead.
i replace binding code on:
$scope.mainGridOptions = {
columns: [
{ field: "ProductID", title: "ID" },
{ field: "ProductName", title: "Product Name" },
{ command: [{ template: "<button class='k-button' ng-click='showDetails(dataItem)'>Show details</button>" }] },
],
pageable: true,
dataSource: {
pageSize: 5,
transport: {
read: function (e) {
dataservice.getImportResultReport().
then(function (data) {
return data;
});
}
}
}
};
After that I don't receive this error but grid stay without data.
Also i attempted do it like:
vm.mainGridOptions = {
columns: [
{ field: "ProductID", title: "ID" },
{ field: "ProductName", title: "Product Name" },
{ command: [{ template: "<button class='k-button' ng-click='showDetails(dataItem)'>Show details</button>" }] },
],
pageable: true
};
$scope.mainGridOptions.DataSource = dataservice.getImportResultReport();
it is also not work.
What i'm doing wrong?
It is example from telerik site. If in binding logic replase dataservice.getImportResultReport() on $http.jsonp('URL FROM EXAMPLE') then it is work.

Kendo grid not showing data only on the initial load, but works fine when stepping through with breakpoints

The problem I'm having is exactly what I said in the title. When I step through my application in the debugger it properly sets everything that needs to be set, but when I just let it go through on its own, it never loads data on the initial attempt, but if i go back and click the same thing again, or any thing else that has to send data to this grid, it will forever work. Even if I go to a page that empties everything in the grid and then go back to one that shows data again.
To me it sounds like a timing issue, but using $timeout() before the data calls doesn't seem to be working. And I set up a broadcast that should only be called after all the data is pulled in and set, and only then should it go to the code for the kendo grid and start painting it on the page.
Like I said stepping through this code line by line on the initial load of the page, it works exactly as it should and pulls in all data that it needs, but letting it just run without me doing that, it never does.
here is hopefully enough code to go off of.
Here is the code for my grid:
$scope.$on('loadRxHistoryGrids', function () {
console.log('user id of ' + pServ.patientId.get());
$scope.activeHistoryGrid = {
pageable: {
pageSizes: [5, 10, 15, 20],
},
dataSource: new kendo.data.DataSource({
type: 'aspnetmvc-ajax',
contentType: "application/json; charset=utf-8",
transport: {
read: {
url: function () {
var x = pServ.patientId.get();
return "api/rx/ActiveRxHistory/" + pServ.patientId.get();
},
dataType: "json",
type: "POST"
},
},
pageSize: 5,
schema: {
model: {
fields: {
rxId: { type: "number" },
refillsLeft: { type: "number" },
shortName: { type: "string" },
unitsRemaining: { type: "number" },
dispenseRefillQuantity: { type: "number" },
description: { type: "string" },
shipDate: { type: "date" }
},
},
data: function (data) {
if (data != undefined) {
$scope.ActiveHistoryCount = data.length;
return data;
} else { return []; }
},
total: function (data) {
return data.length;
},
},
}),
serverPaging: true,
serverSorting: true,
serverFiltering: true,
columns: [
{ hidden: true, field: "rxId"},
{ field: "shortName", title: "DRUG NAME"},
{ field: "refillsLeft", title: "REFILLS LEFT", width: "16%", template: '#= (refillsLeft == null) ? " " : kendo.toString( refillsLeft, "n0")#', attributes: { style: "text-align:left" } },// template: '<div style="text-align:left">#= ((unitsRemaining == null) || (dispenseRefillQuantity == null)) ? " " : kendo.toString(unitsRemaining / dispenseRefillQuantity, "n5")#</div>' },
{ field: "description", title: "STATUS", width: "14%", template: '<div style="text-align:left">#= (description == null) ? " " : description#</div>' },
{ field: "shipDate", title: "SHIPPED DATE", width: "15%", template: '#= (shipDate == null) ? " " : kendo.toString(kendo.parseDate(shipDate), "MM/dd/yyyy") #' }
],
groupable: false,
scrollable: true,
selectable: true,
resizeable: true,
sortable: true,
}
Here is the other code where the broadcast is being sent:
$scope.$on('loadPatientProfileData', function () {
//A lot of data gets and sets are being done here for other things on the
//page, all data is being set in the grid datasource itself
setTimeout(function () {
$rootScope.$broadcast('patientProfile-DataPullFinish');
$rootScope.$broadcast('loadRxHistoryGrids');
}, 100);
});

How to filter a kendo ui datasource serverside

I use a kendo ui scheduler with AngularJS. When the scheduler initially is loaded, the application does not use any filters. When the scheduler is shown to the user, the user must be able to set some filters and submit these filters to the web api. But I'm not able to receive the parameters.
The value of requestStatus can be populated by a multi select:
<select ng-model="requestStatus" id="requestStatus" name="requestStatus" class="form-control" multiple>
<option value="0" label="Open">Open/option>
<option value="1" label="Closed">Closed</option>
<button ng-click="filterPlanboard()" class="btn btn-primary">Submit</button>
My angularjs Controller is like this:
var requestStatus = "";
$scope.filterPlanboard = function () {
console.log($scope.requestStatus);
var requestStatus = $scope.requestStatus;
console.log(requestStatus); //shows: Array ["0","1"] when all items are selected
$scope.schedulerOptions.dataSource.read({
"Status": requestStatus,
"Type": ["70"]
});
//$scope.schedulerOptions.refresh();
};
$scope.$watch("planboardId", function () {
var schedulerDs = new kendo.data.SchedulerDataSource({
//batch: true,
transport: {
read: {
url: "http://localhost:51714/api/Events/Read/" + $scope.planboardId,//"//demos.telerik.com/kendo-ui/service/tasks",
type: "POST",
dataType: "json",
//data: kendo.stringify({"Color": "Green"}),
contentType: "application/json; charset=utf-8"
},
update: {
url: "http://localhost:51714/api/Events/Update",//"//demos.telerik.com/kendo-ui/service/tasks/update",
dataType: "json",
type: "PUT",
contentType: "application/json"
},
create: {
url: "//demos.telerik.com/kendo-ui/service/tasks/create",
dataType: "jsonp"
},
destroy: {
url: "//demos.telerik.com/kendo-ui/service/tasks/destroy",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
}
else if (operation === "update") {
return kendo.stringify({ planboardId: $scope.planboardId, planboardEvent: options });
}
return kendo.stringify(options);
}
},
schema: {
model: {
id: "taskId",
fields: {
taskId: { from: "Id" },
title: { from: "Title", defaultValue: "No title", validation: { required: true } },
start: { type: "date", from: "Start" },
end: { type: "date", from: "End" },
//startTimezone: { from: "StartTimezone" },
//endTimezone: { from: "EndTimezone" },
description: { from: "Description" },
//recurrenceId: { from: "RecurrenceID" },
//recurrenceRule: { from: "RecurrenceRule" },
//recurrenceException: { from: "RecurrenceException" },
ownerId: { from: "OwnerID", defaultValue: 1 },
eventColor: { from: "EventColor", defaultValue: "#333333" }
//isAllDay: { type: "boolean", from: "IsAllDay" }
}
}
});
$scope.schedulerOptions = {
date: new Date("2016/6/26"),
startTime: new Date("2016/6/26 07:00 AM"),
height: 600,
views: planboardViewService.getViews(),
timezone: "Etc/UTC",
eventTemplate: $('#event-template').html(),
ataSource: schedulerDs,
resources: [
{
field: "ownerId",
name: "Owner",
title: "Owner",
dataSource: [
{ text: "Alex", value: 1, color: "#f8a398" },
{ text: "Bob", value: 2, color: "#51a0ed" },
{ text: "Charlie", value: 3, color: "#56ca85" }
]
}
]
};
My Web Api is like this:
[HttpPost]
public IEnumerable<PlanboardEventViewModel> Read(int id, [FromBody] FilterModel filterModel)
{
return _peRepo.GetEvents(id);
}
And my FilterModel:
public class FilterModel
{
public string Status {get;set;}
public string Type {get;set;}
}
When I press the submit button, I can see in fiddler the following json string is shown (in TextView) :
{"Status":["0","1"],"Type":["70"]}

Update function in Kendo UI Grid (using with AngularJs) never fires, using with Local Data

I have a Kendo UI grid, which is bound to an KendoObservableArray. I am using inline edit mode. And my options are declared as below :
valueMapCtrl.lookupMappingDetails = new kendo.data.ObservableArray([]);
valueMapCtrl.gridOptions = {
dataSource: new kendo.data.DataSource({
type: "json",
transport: {
read: function (options) {
options.success(valueMapCtrl.lookupMappingDetails);
},
update: function (options) {
console.log("Update", options);
options.success(options.data);
},
create: function (options) {
console.log("Create", options);
options.data.mappingId = mappingId;
mappingId = mappingId + 1;
options.success(options.data);
},
destroy: function (options) {
console.log("Delete", options);
options.success(options.data);
},
parameterMap: function (options, type) {
// this is optional - if we need to remove any parameters (due to partial OData support in WebAPI
console.log(options, type);
if (operation !== "read" && options.models) {
return JSON.stringify({models: options});
}
},
},
change: function (e) {
console.log("change: " + e.action);
// do something with e
},
error: function (e) {
// handle error
alert("Status: " + e.status + "; Error message: " + e.errorThrown);
},
//data: valueMapCtrl.dynamicData,
schema: {
model: {
id: "mappingId",
fields: {
mappingId: {editable: false, nullable: false, defaultValue: 0},
Col1: {
type: "string",
validation: {
required: true
}
},
Col2: {
type: "string",
validation: {
required: true
}
}
}
}
},
pageSize: 10,
batch: false
}),
columns: [{
field: "col1",
title: "Column 1"
}, {
field: "col2",
title: "Column 2"
}, {
command: /*"destroy"*/ ["edit", "destroy"],
title: " ",
width: "200px"
}],
selectable: "multiple cell",
allowCopy: "true",
//save: function (e) {
// console.log("Save", e);
//},
toolbar: ["create"],
height: 300,
navigatable: true,
filterable: true,
sortable: true,
pageable: true,
editable: "inline"
};
Add record : create fires correctly
Delete record: destroy fires correctly
Update record : nothing happens, no error, all I see in change event sync() action.
But If I declare save as well in my options, that fires correctly.
save: function (e) {
console.log("Save", e); //This fires on each update
},
I am not sure what is wrong in above declaration; browsed through a lot of forums/questions for similar issue but could not get it working. Any help ?
I was able to get it working, posting here in case anyone gets the same issue.
valueMapCtrl.lookupMappingDetails = new kendo.data.ObservableArray([]);
I changed this observable array to normal array and things worked fine after that :
valueMapCtrl.lookupMappingDetails =[];// new kendo.data.ObservableArray([]);
Also, with observable array, I was facing another issue; where cancelling of edit was removing ALL ROWS from the grid. That also worked correctly after this change. Not sure of the reason though and couldn't find any explanation in telerik docs (Whatever I could search).

Resources