I'm having trouble binding a Kendo grid to an angular service call. I have an angular $http
service that has a getData()
method which looks like this:
'use-strict';
payrollApp.factory('dataService', function ($http, $q) {
return {
getData: function () {
var deferred = $q.defer();
$http({
method: 'GET',
url: '/api/apihome/',
}).success(function (data, status, headers, config) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
},
};
});
I then set the grids DataSource
in my controller as follows:
'use-strict';
payrollApp.controller('KendoDataGridController', function KendoDataGridController($scope, dataService) {
var companiesList = dataService.getCompanies();
companiesList.then(function(companies) {
console.log(JSON.stringify(companies, undefined, 2));
$scope.companies = new kendo.data.DataSource({
data: companies,
pageSize: 10
});
}, function(status) {
window.alert(status);
console.log(status);
});
}
);
but my grid is not populating. When I set the DataSource's data manually (hard-coded JSON array) it works fine but not when I'm getting the data in my service call, the JSON array being returned by my service is also a valid JSON array (exactly the same as the one I hard coded). Anybody has an idea? I have a feeling this is a promise issue, but even then I'm setting my $scope's
companies
property when the promise is resolved.
Thanks.
I managed to fix it, there's 2 ways (quite possibly more) of doing this:
1. One is to directly give your kendo grid's datasource the adrress of the Api controller:
There's a full explanation here. But I don't like doing this because I'd rather not hard code API controller addresses in my controller, I prefer to have a service or something return me the data and then pass that on to my grid (Imagine for example wanting to add a token in the
$http
request headers). So after some messing around I got a way of hooking up the grid with my original approach:2. We can just hook up the read function of the grid to another function in our service or whatever, which can be any method returning a promise, i.e. a
$http
call:EDIT
Regarding how to add items that are already available to the grid, and how to have subsequent requests to the server to get new data, this is how I've gone about doing this:
The grid has an
autoBind
property, setting that to false prevents the grid automatically calling the server when the view is loaded. So to add items manually I set this to false, and then add rows to the grid via thedataSource.add()
method. After that callingdataSource.read()
will retrieve more data from the server:Adding items manually to the grid:
$scope.companiesGridOptions.dataSource.data([{id:1,title:"..."}, {id:2,title:"..."}]);
Calling
dataSource.read()
forces a server call to retrieve data:$scope.companiesGridOptions.dataSource.read();
I think you should try refreshing your grid once you populate new data: