Angular JS: JSON data is not getting displayed in ng-Grid - angularjs

I have created MVC 4.0 app using Web API which returns data in JSON format (I am serializing object to json using NewtonSoft.Json) and trying to bind data in ng-Grid. I am receiving data in following format:
"[{\"Name\":\"FIRST_NAME\",\"Value\":\"FIRST_NAME\"},{\"Name\":\"CURRENT_DATE_TIME\",\"Value\":\"CURRENT_DATE_TIME\"},{\"Name\":\"CLIENTID\",\"Value\":\"CLIENTID\"},{\"Name\":\"CALLMODE\",\"Value\":\"CALLMODE\"}, {\"Name\":\"new 321\",\"Value\":null}]"
When i tried to assign same to data: of ng-Grid, each char populated on different row. following is the javascript i have written:
var guidesRespApp = angular.module('guidesRespApp', ['ngGrid']);
//Get Data from restful API.
guidesRespApp.controller('MyCtrl', function ($scope, $http) {
$http.get('/api/datadictionary').success(function (thisdata) {
$scope.myData = thisdata;
});
$scope.filterOptions = {
filterText: '',
useExternalFilter: true,
};
//Setting grid options
$scope.gridOptions = {
data: 'myData',
multiSelect: true,
filterOptions: { filterText: '', useExternalFilter: false },
enableRowReordering: false,
showGroupPanel: false,
maintainColumnRatios: false,
groups: [],
showSelectionCheckbox: true,
showFooter: true,
enableColumnResize: true,
enableColumnReordering: true
};
// $scope.totalFilteredItemsLength = function() {
// //return self.filteredRows.length;
// };
});
If manually assigned like below, data is getting displayed in grid:
$scope.myData = [{"Name":"FIRST_NAME","Value":"FIRST_NAME"},{"Name":"CURRENT_DATE_TIME","Value":"CURRENT_DATE_TIME"},{"Name":"CLIENTID","Value":"CLIENTID"},{"Name":"CALLMODE","Value":"CALLMODE"}];
can anyone please help me to understand how to fix it?
Also i wanted to display count of filtered items when i key in values in filtertext.

As mentioned on http://angular-ui.github.io/ng-grid/ , Data being displayed in the grid is of type array and each element in that array mapped to a row being displayed. So I modified my code like below and it worked for me:
$http.get('http://localhost:12143/api/datadictionary').success(function (thisdata) {
//Convert data to array.
var myData = $.parseJSON(JSON.parse(thisdata));
$scope.myData = myData;
});
even var myData = $.parseJSON(angular.fromJson(thisdata)); also working. Just we need first to parse the data (for this I used JSON.parse()) and then convert to array (for this i used $.parseJSON()).

Try changing the get callback to one of the following:
$http.get('/api/datadictionary').success(function (thisdata) {
$scope.myData = JSON.parse(thisdata);
// or
$scope.myData = angular.fromJson(thisdata);
});
Reference this with regards to how webapi is returning json. ASP.NET WebAPI: How to control string content returned to client?

Related

AngularJS and DataTables refreshing data

My project outputs results to a DataTable from an AngularJS controller function, but I'm running into some strangeness when I try to modify my search params. The first rendering of the table works as expected. But when I select different options and run the search again, extra rows appear in the table, but the info section shows the previous search's row count, and changing the number of rows shown via the length menu causes the new rows to disappear. Here's my table declaration, using attributes to wire up DataTables:
<table ui-jq="dataTable" ui-options="dataTableOptions" id="search-results" class="display nowrap datatable cell-borders" style="width: 100%;">
And this is my AngularJS controller code:
$scope.dataTableOptions = {
dom: "lfBrtip",
lengthMenu: [[25, 50, -1], [25, 50, "All"]],
language: {
emptyTable: 'No items matched your search criteria'
},
buttons: [
{
text: 'Export',
className: 'button button:hover',
extend: 'csv'
}
]
};
$scope.getItemInfo = function (model) {
$http({
method: 'POST',
url: $scope.getUrl('/My/ServerSide/Url'),
data: { model: $scope.model }
}).then(function successCallBack(response) {
$scope.model.SearchResults = response.data;
}, function errorCallback(response) {
alert("There was an error gathering the entity information. Please try again");
});
};
I'm not sure why submitting new queries with different params doesn't simply update the data in the DataTables table. Any suggestions?
I ended up using a bit of an ugly hack to get this to work. Even DataTables author wasn't sure how to get around the issue of using AngularJS with DataTables, so I had to force a reinitialization every time the form posted. I persisted the search params to localStorage, and called location.reload(). Then when the page loads and the AngularJS init() function runs, I pick up the search params and call the search function from inside an Angular document ready function, like this:
$scope.init = function () {
$scope.ValidationErrors = [];
$scope.model = {};
$scope.model.SearchResults = [];
$scope.model.ItemNumber = localStorage.getItem("itemNumber");
$scope.model.StartDate = localStorage.getItem("startDate");
$scope.model.EndDate = localStorage.getItem("endDate");
angular.element(document).ready(function () {
if ($scope.model.ItemNumber) {
$scope.getItemRecords();
}
});
localStorage.clear();
};
And then of course I clear the localStorage after the query. Not terribly elegant, but it'll have to do for now.

Loop through ag-grid data and display values

I am looping through each node of ag-grid data and have to display column values.Attached is the plunkr:
https://plnkr.co/edit/cFBLm7DkAZL5oWbqdyub?p=preview.
I am not able to display the ag-grid data in the console.
var gridOptions = {
defaultColDef: {
sortable: true
},
columnDefs: columnDefs,
animateRows: true,
enableRangeSelection: true,
rowData: rowData,
checkbox : true,
onSelectionChanged : getData
};
new agGrid.Grid(gridDiv, gridOptions);
});
function getData(){
gridOptions.api.forEachNode( function (node) {
console.log("node vaalues are:"+node.data);
});
There are a couple things wrong with your code.
Inorder for onSelectChanged to be called you need to specify how you want row selection to work, try: rowSelection: 'single'
In your plunkr (not your snippet above), your getData function is in the wrong scope. By this I mean all of your code is inside the document.addEventListener, but the getData is not. Because of this, getData doesn't know what gridOptions is.
Updated plunkr: https://next.plnkr.co/edit/cXKVZrT9siHoodVa

UI-GRID display json data

At the moment I am retrieving data from the server.
[
{
id:1,
name:demo,
request: {
id: 1,
localCompany: {
id: 1
}
}
}]
[{ }, { }] so this is how my json object looks.
When I get call the $http service and put it in the gridOptions: {data: this.data}
I get this error in the console window: TypeError: newRawData.forEach is not a function.
data: ng.IPromise<any[]> = this.programService.getRequestsForProgram(this.model.id).then((data: any) => {
console.log(data);
return data;
});
gridOptions: {} = {
data: this.data ,
paginationPageSize: 5
//columnDefs: this.programCountryService.getHeaders()
};
This is the code I am using at the moment.
Any idea how I can get rid of this error? And is it possible that the grid only shows localCompany.Id and not the name:demo?
Try to put the data in $scope.data
Like $scope.data=getdata from server
and then
gridOptions: {} = {
data: $scope.data ,
paginationPageSize: 5
//columnDefs: this.programCountryService.getHeaders()
};
Put data into $scope and than to gridOptions.data = $scope.data.
If you want to show only data for localCompany.id you need to make definition for columnDefs for field request with custom template like:
'<div class="ui-grid-cell-contents">{{ COL_FIELD.id }}</div>'

Kendo HierarchicalDataSource issue binding to Kendo treeview

I have a Kendo HierarchicalDataSource object bound to a Kendo treeview widget.
The HierarchicalDataSource simply returns a one-level-deep json formatted object, but for some reason it won't render in the treeview. It just shows the top node "Dimensions", but renders no data when expanded.
Here is my plunk treeview sample , which contains index.html and script.js .
FYI for script.js :
$scope.dimenDataSource is the Kendo HierarchicalDataSource object which uses the transport property to call my method getDimensionsFromServer2 and also specify the schema.
Another FYI: In getDimensionsFromServer2() I have two ways of returning my test data. The dataFlat var returns a flat array, which renders fine. The data object has nested data, but does NOT render in treeview.
I'm not sure what's going wrong.
Thank you,
Bob
**** UPDATE ****
The problem was the incorrect placement of the schema setting (see my answer):
settings.dimenDataSource = new kendo.data.HierarchicalDataSource({
transport: {
read: function(options){
datacontext.getDimensionsFromServer().then(function (data) {
var rootnode = [{ name: "Dimensions", items: data.data }];
options.success(rootnode);
});
},
schema: {
model: { children: "items" }
},
loadOnDemand: false
}
});
My mistake was in the schema placement, which I had inadvertently placed in the transport option. It should placed at the same level, not within it.
Here's is the corrected version:
settings.dimenDataSource = new kendo.data.HierarchicalDataSource({
transport: {
read: function(options){
datacontext.getDimensionsFromServer().then(function (data) {
var rootnode = [{ name: "Dimensions", items: data.data }];
options.success(rootnode);
});
},
loadOnDemand: false
},
schema: {
model: { children: "items" }
}
});

Datatable JSON Formatting error

Hi I am getting this warning message even though the results are showing in rows
DataTables warning (table id = 'list'): DataTables warning: JSON data from server could not be parsed. This is caused by a JSON formatting error
while trying to invoking a web service call using angularjs and loading the results in Datatable.Here is my controller.js
var clustersApp = angular.module('clustersApp', []);
clustersApp.controller("nodeListCtrl", function ($scope, $http) {
$http.get('http:demo.json').then(function(res){
$scope.listData = res.data.nodes;
});
});
and datatable js
$(document).ready(function () {
$("#list").dataTable({
"sPaginationType":"full_numbers",
"bFilter": true,
"bInfo": true,
"bServerSide": true,
"oLanguage": {
"sSearch": "",
},
"fnPreDrawCallback": function(oSettings,json) {
$('.dataTables_filter input').addClass('form-control input-sm');
$('.dataTables_filter input').attr('placeholder', 'Enter Ip to search');
},
"asStripClasses": [],
"aoColumnDefs": [{
"bSortable": false,
"aTargets": ["no-sort"]
}]
});
});
Can any one please let me know why is it showing the error.Am very new to JSON.Please help me in sorting the issue.

Resources