Angular ngGrid data presentation - javascript

I'm new to Angular and my experience with Javascript is not very extensive. I am failing to show data in ngGrid using following code. What is the problem?
In essence. I am loading data from a web-service, performing a transform (pivot) on it and then I want to present it in a grid.
Please see the following
app.js -> starting poing
var konstruktApp= angular.module('konstruktApp',['ngGrid']);
dataService.js -> web service call
'use strict';
konstruktApp.service('DataService',function DataService($http){
var callHttp = function(){
delete $http.defaults.headers.common['X-Requested-With'];
return $http.get("http://83.250.197.214/konstrukt.service/Konstrukt.SL.DummyBudgetService.svc/GetDummyBudgetData/");
};
return {
getDummyData: callHttp
};
});
ngGridController.js -> where the logic resides...
$scope.getData = DataService.getDummyData;
$scope.gridOptions = {data:'result'};
var getData = function() {
$scope.getData().then(function (response) {
var res = pivotData(response.data);
$scope.result = res.data.PivotedRows;
$scope.columns = res.cols;
console.log('from the success handler at ' + new Date());
}, function (reason) {
console.log('failed: ');
console.log(reason);
});
};
..and here is the logic that "pivots" the data
var pivotData = function(data) {
var firstColumn = "Dim1";
var secondColumn = "Period";
var columns = [];
columns.push({
field: firstColumn,
enableCellEdit: false
});
var pivotedArray = {};
pivotedArray.PivotedRows = [];
var rowItems = [];
var rowArray = {};
var previusFirstColumnValue = -1;
var firstColumnValue = 1;
//for each row
for (var i = 0; i < data.Rows.length; i = i + 1) {
//firstColumnValue = $scope.dataCollection.Rows[i].FindCell.Cells[firstColumn].Value;
firstColumnValue = findCell(data.Rows[i].Cells, firstColumn).Value;
//var secondColumnValue = data.Rows[i].Cells[secondColumn].Value;
var secondColumnValue = findCell(data.Rows[i].Cells, secondColumn).Value;
//if first column value has changed, add new row
if (firstColumnValue != previusFirstColumnValue) {
if (i !== 0) {
for (var j = 0; j < rowItems.length; j = j + 1) {
rowArray[rowItems[j].name] = rowItems[j].value;
}
pivotedArray.PivotedRows.push( rowArray);
rowArray = {};
rowItems = [];
}
rowItems.push({
name: firstColumn,
//value: $scope.dataCollection.Rows[i].Cells[firstColumn].Value
value: findCell(data.Rows[i].Cells, firstColumn).Value
});
}
//if (columns.indexOf({field: secondColumnValue}) == -1) {
if (i < 12) {
columns.push({
field: secondColumnValue,
editableCellTemplate: "<input ng-class=\"'colt' + col.index\" ng-input=\"COL_FIELD\" ng-blur=\"lostFocus()\" ng-model=\"COL_FIELD\" ng-change=\"dataChanged(col,row,row.entity)\"/>",
enableCellEdit: true
});
}
rowItems.push({
name: secondColumnValue,
value: findCell(data.Rows[i].Cells, secondColumn).Value
});
previusFirstColumnValue = firstColumnValue;
}
for (var k = 0; k < rowItems.length; k = k + 1) {
rowArray[rowItems[k].name] = rowItems[k].value;
}
// $scope.columns = columns;
pivotedArray.PivotedRows.push( rowArray);
return {data: pivotedArray, cols: columns};
};
plnkr: http://plnkr.co/edit/ZqC7696xGbUtuWGIvnYs?p=preview
EDIT: The data correlation rows<-> columns is correct, I suspect there is something wrong with data in the pivotedArray.PivotedRows array.

It turned out that moving the code to a new plnkr made the difference. Now, thats a few hours of my life that I want back :)

Related

Instantiate the value of an array from one function to a different function in jquery

I want to get the result of a jquery function attached to an id and change e.g
<script>
$('#dateID').change(function(){
var bookday = $(this).val();
$.post('getDates.php',{postbookday:bookday},
function(data){
var array = JSON.parse("[" + data + "]");
var list = [];
var newArray = array.flat([2]);
for (var i = 0; i < newArray.length; i++) {
list.push(newArray[i]);
};
if (list.length>96) {
alert("Sorry, day fully booked!");
}
else{
function selectedTime(list) {
return [a, b, c];
}
var result = selectedTime(list);
var myArray = [];
for (var i=0; i < result[2].length; i++) {
if (result[2][i] === '09:00') {
myArray.push(['09:00','10:00']);
}
if (result[2][i] === '10:00') {
myArray.push(['10:00','11:00']);
// here is myArray
}
}
}
});
});
</script>
and then use it as the input in another different function below:
$('#disableTimeRangesExample').timepicker(
{
'disableTimeRanges': myArray
}
);
How do I get myArray in the next function? considering that it is not static.
You have two options:
1. save the variable in outer scope:
var myArray;
$('#selectedDate').change(function(
...some computations...
myArray = [['1pm', '2pm']];
});
$('#disableTimeRangesExample').timepicker({
'disableTimeRanges': myArray
});
2. save in jQuery data
$('#selectedDate').change(function(
...some computations...
$(this).data('array', [['1pm', '2pm']]);
});
$('#disableTimeRangesExample').timepicker({
'disableTimeRanges': $('#selectedDate').data('array') || []
});
As a side note you will probably also need to update timepicker on each change.
EDIT: to update time picker on change of the input you need to put this inside change event:
$('#dateID').change(function(){
var bookday = $(this).val();
$.post('getDates.php',{postbookday:bookday},
function(data){
var array = JSON.parse("[" + data + "]");
var list = [];
var newArray = array.flat([2]);
for (var i = 0; i < newArray.length; i++) {
list.push(newArray[i]);
};
if (list.length>96) {
alert("Sorry, day fully booked!");
}
else{
function selectedTime(list) {
return [a, b, c];
}
var result = selectedTime(list);
var myArray = [];
for (var i=0; i < result[2].length; i++) {
if (result[2][i] === '09:00') {
myArray.push(['09:00','10:00']);
}
if (result[2][i] === '10:00') {
myArray.push(['10:00','11:00']);
// here is myArray
}
}
$('#disableTimeRangesExample').timepicker(
'option', {'disableTimeRanges': myArray}
);
}
});
});
$('#disableTimeRangesExample').timepicker();

Wait $.each untill first queue not finished

Below is my code. if we use set timeout function we got all data but we not use we are not getting inspection data which is coming from my local db. i want use deferred and promises in my code. Thanks in advance.
function onclickToCall() {
this.$('.check-list > .check-list-box').each(function (i) {
var j = i + 1;
var answer_req = $(this).attr("data-isReq");
var checklist_guid = $(this).attr("data-guid");
var question_type = $(this).attr("data-type");
var yes_no = $("input:radio[name='radio_" + j + "']:checked").val();
var notes = $(this).find('#txtAreaNotes_' + j).val();
var attachment_url = $(this).find(".txtCameraImage").attr("data-path");
var appConfig = DriverConnectApp.State.get('config_settings');
var item = {};
item.checklist_guid = checklist_guid;
item.yes_no = yes_no;
item.attachment_url = attachment_url;
item.notes = notes;
if (question_type == 2) { // For Vehical visual inspection
var dataPromise = that.getInspectionData(checklist_guid);
dataPromise.done(function (response, vh_image) {
var inspectionItem = {};
inspectionItem.vh_url = vh_image;
inspectionItem.details = response;
item.vh_inspection = inspectionItem;
that.detailsArr.push(item);
});
} else {
item.vh_inspection = {};
that.detailsArr.push(item);
}
});
// after finish and push all data we need to call function here
test();
}
getInspectionData: function (checklist_guid) {
var that = this;
var deferred = $.Deferred();
that.dbchecklist.getVehicleInspectionlist(checklist_guid, function (data, res) {
var details = [];
if (data.length) {
var img = data[0].vh_image;
var arr = JSON.parse(data[0].vh_details);
for (var k = 0; k < arr.length; k++) {
var items = {};
items.number = arr[k].number;
items.notes = arr[k].notes;
items.attachment_url = arr[k].attachment_url;
details.push(items);
}
deferred.resolve(details, img);
} else {
deferred.resolve(details, img);
}
});
return deferred.promise();
}

How to add dynamically HTML element using JavaScript and Firefox Add-on SDK

I am developing a simple add-on with Firefox SDK that allows the user to review the stored data.
I would like to show the items in a panel with a table. The table is created dynamically with the data incoming from the data-base. Firstly, In the JavaScript code I create the items with their properties, then I create a table with the properties as row and I append the items with the value of each properties.
I have some problems: the table has only the item's name as first row and the properties name as first column without the value in the cells. It seems that the code is not executed in order, but it seems that the faster functions are executed first.
This is the code:
self.on('message', function() {
var container = $('#container');
container.empty();
items = [];
self.port.emit('getItem');
});
self.port.on('items', function(response) {
var ok = 0;
var items = [];
var table = $('#tableContainer #table').clone();
var container = $('#container');
table.append("<tr id=first><th> </th></tr>");
var json = eval('('+ response + ')');
for (var i = 0, len = json.length; i < len; ++i) {
var item = {
id: json[i],
properties: []
};
items.push(item);
}
items.forEach ( function(item) {
table.find('#first').append("<th id="+item.id+">"+item.id+"</th>");
self.port.emit('detailsItem', item.id);
self.port.on('details'+item.id, function(response) {
var details = eval('('+ response + ')');
var description = [];
ndet = details.length;
var len = details.length;
for (var i = 0; i < len;) {
var detail = {
dimension : details[i].dimension,
value : details[i].value
}
description.push(detail);
++i;
}
item.properties = description;
});
});
self.port.emit('getDimension');
self.port.on('dimension', function(response) {
var dimensions = eval('('+ response + ')');
for(var cont = 0, l = dimensions.length; cont < l; ++cont) {
table.append("<tr id=dimension"+cont+"><td>"+dimensions[cont]+"</td></tr>");
items.forEach( function(item) {
var prop = [];
prop = item.properties;
var lun = prop.length;
for( var p =0;p < lun;) {
if(item.properties[p].dimension == dimensions[cont]) { table.find('#dimension'+cont).append("<td>"+item.properties[p].value+"</td>");
}
else {
table.find('#dimension'+cont).append("<td> --- </td>");
}
++p; }
});
};
});
container.append(table);
});

JavaScript - Generate Kendo Ui Grid using xml Data

I've Been using XSLT to display my xml page. I make use of the following to get the data from the xml file:
< xsl:value-of
select="ClinicalDocument/component/structuredBody/component[3]/section/text/table/tbody"/
>
After this, I have the following javascript to clean up the data and do the conversion:
-----------Get Content for Grids----------
//Split Content into array
var purposeArray = document.getElementById('purposeOfVisit').innerHTML.split("\n");
var activeProblemArray = document.getElementById('activeProblems').innerHTML.split("\n");
//------------ Remove All Unwanted Values-----------\\*/
var newDataString ="";
for( var k = 0; k < purposeArray.length; k++ )
{
newDataString += purposeArray[k] + "__";
}
newDataString = newDataString.replace(/ /g,"");
newDataString = newDataString.replace(/__________/g,"__-__");
var newDataArray = newDataString.split("__");
//------------- Save Values in final Array -------------\\*/
var semiFinalArray = new Array();
for( var x=0; x < newDataArray.length; x++)
{
if(newDataArray[x].length != 0)
{
semiFinalArray.push(newDataArray[x]);
}
}
var finalArray = new Array();
var counter = 0;
//------------ Find Number of Columns in row ------------\\*/
var numberOfRows = document.getElementById('numberOfRows').innerHTML;
var numberOfColumns = document.getElementById('numberOfColumns').innerHTML;
var columnsPerRow = parseInt(numberOfColumns) / parseInt(numberOfRows);
//------------------------------Testing ------------------------------//
var dataNamePre = "dataValue";
var temporaryArray = new Array();
var dataName;
//----------- Generate Grid Values -----------//
for( var b=0 ; b < semiFinalArray.length ; b = b + columnsPerRow)
{
var problemComment = "";
counter = 0;
var obj;
for( var a=0 ; a < columnsPerRow ; a++)
{
dataName = dataNamePre + counter.toString() + "";
//-------Generate Grid Titles------//
temporaryArray.push("Title " + (counter+1));
var key = "key"+a;
obj = { values : semiFinalArray[b+a] };
var problemComment = "";
finalArray.push(obj);
counter++;
}
}
//---------------------Generate GridArray---------------------------//
var gridArray = [];
var gridArrayHead = new Array();
counter = 0;
var objectValue = new Array();
for( var x = 0; x < finalArray.length; x++ )
{
objectValue = { head:temporaryArray[x], values: finalArray[x].values }
gridArray.push(objectValue);
}
var provFacilities = [];
for( var x = 0; x < finalArray.length; x++ )
{
provFacilities[x] =
{
head:temporaryArray[x], values: finalArray[x].values
}
}
//alert(gridArray);
$("#grid").kendoGrid(
{
columns:
[{
title:gridArray.head,
template:'#= values #'
}],
dataSource: {
data:finalArray,
pageSize:10
},
scrollable:false,
pageable:true
});
This may be a roundabout method, but I'm still prettry new to this method of coding.
Currently, all the data is being presented in one column, with the last value in my temporaryArray as the title for the column.
Everything works until I try to set the DataSource for the Kendo Grid. When working in the columns property in the grid, I made the following change:
title:gridArray[0].head
When this is done, the title is changed to the first value in the array.
What I want to know is how can I generate columns in the Kendo Grid According to the title? Is there a way to loop through all the values and create the objects from there, seeing that the date that is being sent to the grid are objects in an Array?
What I basically want is something to make this work, without the repitition:
var myGrid = $("#grid").kendoGrid( { columns: [ {
title: temporaryArray[0],
field: finalArray[0].values }, {
title: temporaryArray[1],
field: finalArray[1].values }, {
title: temporaryArray[2],
field: finalArray[2].values }, {
title: temporaryArray[3],
field: finalArray[3].values }, {
title: temporaryArray[4],
field: finalArray[4].values } ]
)};
Any help appreciated, thanks!
This issue has been fixed using the following coding:
var arrayData = [];
for( var x = 0; x < semiFinalArray.length; x=x+5 )
{
var tempArr = new Array();
for( var y = 0; y < 5; y++ )
{
var num = x + y;
tempArr.push(semiFinalArray[num]);
}
arrayData.push(tempArr);
}
var dataTitles = [];
for( var x = 0; x < titleArray.length; x++ )
{
var head = "";
head = titleArray[x];
head = head.replace(/ /g,"");
dataTitles.push(head);
}
var counter = 0;
var columnDefs = [];
for (var i = 0; i < columnsPerRow.length; i++)
{
if (counter == (columnsPerRow - 1))
{
counter = 0;
}
columnDefs.push({ field: dataTitles[counter], template: arrayData[i].values });
counter++;
}
// Create final version of grid array
var gridArray = [];
for (var i = 0; i < arrayData.length; i++)
{
var data = {};
for (var j = 0; j < dataTitles.length; j++)
{
data[dataTitles[j]] = arrayData[i][j];
}
gridArray.push(data);
}
// Now, create the grid using columnDefs as argument
$("#grid").kendoGrid(
{
dataSource:
{
data: gridArray,
pageSize: 10
},
columns: columnDefs,
scrollable: false,
pageable: true
}).data("kendoGrid");
With this, the data is displayed in the DataGrid.

JQGrid MultiSelect getting the column data

Is there a way for the JQGrid to return an array of column Data for using multiSelect as opposed to just an array of rowIds ?
At the moment I can only return the last column data that was selected.
jQuery("#buttonSelected").click(function() {
var ids = jQuery("#relatedSearchGrid").getGridParam('selarrrow');
var count = ids.length;
for (var i = 0; i < count; i++) {
var columnData = $("#relatedSearchGrid").find("tbody")[0].rows[$("#relatedSearchGrid").getGridParam('selrow') - 1].cells[1].innerHTML;
alert("In the loop and " + columnData );
}
if (count == 0) return;
var posturl = '<%= ResolveUrl("~") %>Rel******/AddSelected****/' + ids;
if (confirm("Add these " + count + " Docs?")) {
$.post(posturl,
{ ids: columnData },
function() { jQuery("#relatedSearchGrid").trigger("reloadGrid") },
"json");
}
})
Use getRowData to get the data for each row:
var rowData = $("#relatedSearchGrid").getRowData(ids[i]);
var colData = rowData.Name_Of_Your_Column;
var userListjqGrid = $('#UserListGrid'),
selRowId = userListjqGrid.jqGrid('getGridParam', 'selrow'),
userId = userListjqGrid.jqGrid('getCell', selRowId, 'UserId'),
userName = userListjqGrid.jqGrid('getCell', selRowId, 'UserName'),
subIds = $(subgridTableId).getGridParam('selarrrow'),
accessRuleIds = [];
for (var i = 0; i < subIds.length; i++) {
accessRuleIds[i] = $(subgridTableId).getRowData(subIds[i]).AccessRuleId;
}

Categories