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

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.

Related

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 share code in angular js (concept of code resuability in angular js?

i am new to angular js and i want to share and make certain codes reusable. i have tried to do that using services and factory. But i am getting error.
'use strict';
angular.module('myApp.ctrls')
.controller('Ctrl_HubStockOnHandMode', function($http, $scope, reportService) {
$scope.HubStockOnHandModeGridOptions = {
dataSource: {
type: "jsonp",
transport: {
read: function(e) {
reportService.WebAPI('abc/BIUMo', {
EnvironmentCode:'JMVH',
OrderBy: getOrderBy(e.data.sort)
}).then(function (d) {
$scope.data = d;
e.success(d.Data);
});
}
},
serverPaging: true,
serverSorting: true
},
height:config.GridHeight,
scrollable:true,
sortable: {
mode: "single",
allowUnsort: true
},
filterable: {
extra: false,
operators: {
string: {
startswith: "Starts with",
eq: "Is equal to",
neq: "Is not equal to",
contains: "Contains"
}
}
},
pageable: false,
columns: [
{
field: "RowNumber"
,title: "No."
,width: "50px"
,sortable:false
,filterable: false
},
{
field: 'ItemCTSH'
,title:'Item'
,template: "<div kendo-tooltip title='#= ItemCT #' > #= ItemCTSH # </div>"
,filterable: {
ui: itemFilter
}
},
]
};
}
//Get Item List
$http.get('http://webapi.dashboard.hcmisonline.org/api/OID_WebApi/IssuedItemList')
.success(function (data) {
$scope.items = data.Data;
});
function itemFilter(element) {
element.kendoAutoComplete({
dataSource: $scope.items
});
}
}
});
I want to reuse the functions like the Get item. i have other pages/grids that use exactly this code, except changing the environment code
how to i solve this issue?
thanks

Using AngularJS and KendoGrid

I am learning AngularJS and trying to use the Telerik KendoGrid in a directive. I have a directive that that will access a service and get some data. Part of the data will be used to populate an observable array in the directive. The html that is associated to that directive has another directive within it that will create a kendoGrid that should be editable. When I click on the update button I get an undefined error and the grid data disappears.
I define my array as follows:
$scope.currentData.event.submissionDates = new kendo.data.ObservableArray([
]);
and on success of call push the data into the array.
the grid is called as follows in the html:
<submission-grid class="grid-16" event="currentData.event" ng-show="currentData.event.eventID"></submission-grid>
This directive calls the following html file:
<div kendo-grid="grid"
k-columns="gridColumns"
k-selectable="true"
k-on-change="selected = data"
k-options ="mainGridOptions "
k-editable ="{'mode': 'inline', 'update': 'true'}"
and the backing js is:
(function () {
angular.module('app.submissionGrid', [])
.directive('submissionGrid', function () {
var ctrlr = function ($scope) {
$scope.gridColumns = [{
field: "SubmissionDueDate",
title: "Due Date",
format: "{0:MM/dd/yyyy}",
width: "100px"
}, {
field: "Source",
title: "Agency",
width: "100px"
}, {
field: "SubmissionFiledDate",
title: "Filed Date",
format: "{0:MM/dd/yyyy}",
width: "100px"
}, {
field: "SeverityCategory",
title: "Severity Category",
width: "100px"
}, { command: ["edit", ], title: " ", width: "200px" }
];
$scope.mainGridOptions = {
dataSource: {
data: $scope.event.submissionDates,
schema: {
model: {
id: "ReportId",
fields: {
SubmissionDueDate: { type: "string" },
Source: { type: "string" },
SubmissionFiledDate: { type: "string" },
SeverityCategory: { type: "string" }
}
}
},
}
}
}
return {
restrict: 'E',
templateUrl: 'App/Event/SubmissionGrid/submissionGrid.html',
controller: ctrlr,
transclude: false,
scope: {
event: '='
}
};
})
})();
Any advice would be appreciated.

Kendo UI Grid foreign key column using Angular directives

I'm trying to make a Kendo Grid that has 2 foreign key columns using the Angular directives for Kendo. I am able to get one to work, but not the other (independent of each other). If I comment one out the other will work and vice versa, but either way only one will work. Abbreviated sample code is below.
invoicesController.js
app.controller('invoicesController', [
'$scope', '$rootScope', 'config', 'dataFactory', function($scope, $rootScope, config, dataFactory) {
$rootScope.title = 'Invoices';
$scope.filterCustomers = [];
$scope.filterStatuses = [];
$scope.invoiceGrid = null;
var _refreshCustomers = function () {
dataFactory.get(_.string.format('{0}customers', config.apiUrl)).success(function (result) {
$scope.filterCustomers = _.map(result, function (cust, key) {
return {
text: cust.name,
value: cust.id
}
});
});
};
var _refreshStatuses = function() {
dataFactory.get(_.string.format('{0}invoicestatuses', config.apiUrl)).success(function(result) {
$scope.filterStatuses = _.map(result.data, function(status, key) {
return {
text: status.name,
value: status.id
}
});
_initializeGrid();
});
};
var _refreshData = function () {
_refreshCustomers();
_refreshStatuses();
};
_refreshData();
var _initializeGrid = function() {
$scope.invoiceGrid = {
dataSource: {
transport: {
read: _.string.format('{0}invoices', config.apiUrl),
},
schema: {
data: 'data'
},
pageSize: 15,
sort: { field: 'invoiceDate', dir: 'asc' }
},
columns: [
{ title: 'Subject', field: 'subject', type: 'string', width: '30%'},
{ title: 'Number', field: 'number', width: '12%' },
{ title: 'Customer', field: 'customer.id', values: $scope.filterCustomers, width: '15%' },
{ title: 'Status', field: 'status.id', values: $scope.filterStatuses, width: '14%' },
{ title: 'Total', field: 'invoiceTotal', type: 'number', format: '{0:c2}', width: '10%' },
{
title: 'Updated', field: 'updatedOn', type: 'date', format: '{0:d}', width: '19%',
template: '#=lastUpdated#'
}
],
scrollable: false,
sortable: true,
filterable: true,
pageable: true
};
}
}
]);
dataFactory.js (GET method)
return $http({
url: url,
method: 'GET',
data: data,
});
list.html
<div data-kendo-grid data-k-ng-delay="invoiceGrid" data-k-options="invoiceGrid" class="top"></div>
I was able to get this to work using route resolve.
Basically, when you're defining your routes, you can set resolvers. In this case, I'm resolving customers and statuses which you will also see as arguments on the projectsController
app.js (routing config)
// Projects
$routeProvider.when('/projects', {
templateUrl: '/app/views/projects/list.html',
controller: 'projectsController',
resolve: {
customers: ['customerService', function (customerService) {
return customerService.getCustomers();
}],
statuses: ['projectService', function (projectService) {
return projectService.getStatuses();
}]
}
});
projectsController.js (abbreviated)
app.controller('projectsController', [
'$scope', '$rootScope', 'config', 'customers', 'statuses', function($scope, $rootScope, config, customers, statuses) {
// Set the options from the injected statuses (from the route resolver)
$scope.statusOptions = _.map(statuses.data.data, function(status) {
return { value: status.id, text: status.name }
});
....
// Kendo grid column definition
columns: [
{ title: 'Status', field: 'status.id', values: $scope.statusOptions, width: '15%' },
]
}]);

How to create Grid in sencha touch 2.3.0 populate data from a REST webservice

I need to display report in Grid / Table in Sencha Touch 2.3.0. Is there any build in function to do so.
The store needs to populate data from a REST webservice call.
For loading data you can use Ext.data.Store configured with REST proxy Ext.data.proxy.Rest
For displaying data from store you can use Ext.grid.Grid of Ext.dataview.DataView
I do this all the time with something like this:
(Though I haven't worked with the Grid, I'm quite sure the same principles apply...)
Ext.define('App.controller.GridController', {
extend : 'Ext.app.Controller',
config: {
refs: {
getApiButton: 'button[action=getApiData]'
},
control: {
'getApiButton' : {
tap : 'onButtonTap'
}
}
},
onButtonTap : function(field, value) {
var that = this;
Ext.Ajax.request({
url : someWebServiceUrl,
method: 'GET',
success: function (result, request) {
var res = Ext.decode(result.responseText);
if (res.success === true && res.data != false) {
var recipient = {
name: res.data[0].displayname,
picId: res.data[0].pictureid,
gender: res.data[0].gender
};
var mod = Ext.define('App.model.GradingPopModel', {
extend: 'Ext.data.Model',
config: {
fields: [
'name',
'picId',
'gender'
]
}
});
/* == this is probably where you want to make your changes to apply the model to the grid template
the sencha website has this:
data: {'items': [
{ 'name': 'Lisa', "email":"lisa#simpsons.com", "phone":"555-111-1224" },
{ 'name': 'Bart', "email":"bart#simpsons.com", "phone":"555-222-1234" },
{ 'name': 'Homer', "email":"home#simpsons.com", "phone":"555-222-1244" },
{ 'name': 'Marge', "email":"marge#simpsons.com", "phone":"555-222-1254" }
]}
*/
var store = Ext.create('Ext.data.Store', {
model: mod,
storeId:'recipStore'
});
store.add(recipient);
store.setData(recipient);
store.load();
var gridView = Ext.ComponentQuery.query('#gridViewId')[0];
gridView.setStore(store);
}
},
failure: function (result, request) {
console.log('api call was a failure');
},
scope: this
});
}
});
Now of course your data won't have "displayname, gender" etc.. but you should get the point.
I also found a working example here (I find it very sad that Sencha allows broken demos on their own website): http://demo.rasc.ch/eds/touch23/grid/grid/index.html

Resources