I'm using a service to retrieve a JSON file whose contents are going to be the source data for the grid. The service works and fetches the data, but my grid renders its basic layout, like it should but there's no data in it. I need to be able to grab data async from a service, and use that data to populate my grid, how can I do that?
app.js
var app = angular.module('myApp', ['ngGrid']);
//service call to ge the data
app.service('MyService',function($http){
var get = function(){
return $http.get('data.json');
}
return {
get: get
}
});
//controller where the grid is supposed to live
app.controller('NewController',function($scope,MyService) {
$scope.get = MyService.get;
$scope.message = "this is the new controller message";
$scope.gridOptions = {
data: $scope.get
}
var getData = function() {
$scope.get().then(function (data) {
$scope.gridOptions.data = data['data'];
console.log('from the success handler');
console.log($scope.gridOptions.data);
}, function (reason) {
console.log('failed: ');
console.log(reason)
})
}
getData();
});
//not used in this example
app.controller('MyCtrl',function($scope){
$scope.data = "This is some data";
})
HTML
<html ng-app="myApp">
<head lang="en">
<meta charset="utf-8">
<title>Getting Started With ngGrid Example</title>
<link rel="stylesheet" type="text/css" href="css/ng-grid.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<script src="libs/jquery-1.9.1.js"></script>
<script src="libs/jquery-ui-1.9.1.custom.min.js"></script>
<script src="libs/angular-1.2.js"></script>
<script src="libs/ng-grid-2.0.11.debug.js"></script>
<script src="scripts/app.js"></script>
<style>
.gridStyle {
width: 400px;
height: 300px
}
</style>
</head>
<body >
<div ng-controller="NewController">
<div class="gridStyle" ng-grid="gridOptions"></div>
</div>
</body>
I don't see any errors in the console. It looks as if the gridOptions is not being set in the success handler as it should be. Everything prints out to the console fine, so I know the data it should be getting is correct. How can I use my service to fill an ngGrid table?
With ng-grid you have to first initialize your data source.
Made Corrections to your code:
$scope.gridOptions = {data:'result'};
And the data source should be an array:
$scope.result = data['data'].data;