colouring of ui bootstrap calendar(datepicker) giving problems after ajax call - angularjs

html code:
<style>
.full button span {
background-color: limegreen;
border-radius: 32px;
color: black;
}
.partially button span {
background-color: orange;
border-radius: 32px;
color: black;
}
.appointment>button {
color: black;
background-color: red;
}
.holidays>button {
color: black;
background-color: green;
}
</style>
<div>
<pre>Selected date is: <em>{{dt | date:'fullDate' }}</em></pre>
<div style="display:inline-block; min-height:290px;">
<uib-datepicker ng-model="dt" class="well well-sm" datepicker-options="inlineOptions" ng-change="dateSelected()" date-disabled="enableRequired(date, mode)" custom-class="dayClass(date, mode);"></uib-datepicker>
angularjs colour working code:
$scope.today = function() {
console.log($rootScope.dt);
var newdate = new Date($rootScope.dt);
newdate.getDate();
newdate.getMonth()+1;
newdate.getFullYear();
d=newdate.getFullYear()+"-"+(newdate.getMonth()+1)+"-"+newdate.getDate();
console.log("after cj\hnage"+d);
holidays = new Array();
var promise = servicePOST.send(appConstants.BASE_MS_URL + 'Dcrs/activityDay.php',{
"date":d
}).then(function(result) {
$scope.dcrlocked = result.dcrlocked;
$scope.leaves = result.leaves;
console.log(result.holidays);
//$scope.holidays = result.holidays;
for(i=0;i<result.holidays.length;i++)
{
holidays.push(new Date(result.holidays[i].date.replace(/-/g,',')));
}
alert(holidays.length);
return result.holidays;
});
/*promise.then(function(result) {
alert("holiday length after service post"+holidays.length);
$scope.dayClass= function(date, mode) {
if (mode === 'day') {
var dateToCheck = new Date(date);
for(var i = 0; i < holidays.length ; i++) {
if(areDatesEqual(holidays[i], dateToCheck)){
return 'appointment';
}
}
}
return '';
};
}); */
$rootScope.dt = new Date();
};
$scope.today();
$scope.clear = function() {
$rootScope.dt = null;
};
$scope.inlineOptions = {
minDate: new Date(),
showWeeks: false
};
$scope.dateOptions = {
formatYear: 'yy',
maxDate: new Date(2020, 5, 22),
minDate: new Date(),
startingDay: 1
};
// Disable weekend selection
function disabledasda(data) {
var date = data.date,
mode = data.mode;
return mode === 'day' && (date.getDay() === 0 || date.getDay() === 6);
}
$scope.toggleMin = function() {
$scope.inlineOptions.minDate = $scope.inlineOptions.minDate ? null : new Date();
$scope.dateOptions.minDate = $scope.inlineOptions.minDate;
};
$scope.toggleMin();
$scope.open1 = function() {
$scope.popup1.opened = true;
};
$scope.setDate = function(year, month, day) {
$rootScope.dt = new Date(year, month, day);
};
$scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
$scope.format = $scope.formats[0];
$scope.altInputFormats = ['M!/d!/yyyy'];
$scope.popup1 = {
opened: false
};
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
var afterTomorrow = new Date();
afterTomorrow.setDate(tomorrow.getDate() + 1);
$scope.events = [
{
date: tomorrow,
status: 'full'
},
{
date: afterTomorrow,
status: 'partially'
}
];
$scope.enableRequired = function(date, mode){
$scope.holidaysdateshardcoded = [
new Date(2016,04,03),
new Date(2016,04,08),
//new Date(2016,2,16),
new Date()
]
var isHoliday = true;
for(var i = 0; i < $scope.holidaysdateshardcoded.length ; i++) {
if(areDatesEqual($scope.holidaysdateshardcoded[i], date)){
isHoliday = false;
}
}
return ( mode === 'day' && isHoliday );
};
function areDatesEqual(date1, date2) {
return date1.setHours(0,0,0,0) === date2.setHours(0,0,0,0)
}
$scope.dayClass = function(date, mode) {
var appointments = [
new Date(2016,04,03),
new Date(2016,04,08),
new Date(),
]
if (mode === 'day') {
var dateToCheck = new Date(date);
for(var i = 0; i < appointments.length ; i++) {
if(areDatesEqual(appointments[i], dateToCheck)){
return 'appointment';
}
}
}
return '';
};
$scope.dateSelected = function(){
var appointments = [
new Date(2016,04,03),
new Date(2016,04,08),
new Date(),
];
var dateSelected = new Date($rootScope.dt);
for(var i = 0; i < appointments.length ; i++) {
if(areDatesEqual(appointments[i], dateSelected)){
performAction();
}
}
};
function performAction(){
location.href='#/data';
}
with the above angularJS code, the dates get coloured but next when i fetch an array from the database and use promise to wait till data come and than apply the colour using dayclass as in the following angularJS code, it does not work (no colour gets applied to the particular dates coming in holidays array). the data comes properly and i manipulate it to the format required and passs the dates from the holidays arry. but it does'nt work.
angularJS code that does not work:
$scope.today = function() {
console.log($rootScope.dt);
var newdate = new Date($rootScope.dt);
newdate.getDate();
newdate.getMonth()+1;
newdate.getFullYear();
d=newdate.getFullYear()+"-"+(newdate.getMonth()+1)+"-"+newdate.getDate();
console.log("after cj\hnage"+d);
holidays = new Array();
var promise = servicePOST.send(appConstants.BASE_MS_URL + 'Dcrs/activityDay.php',{
"date":d
}).then(function(result) {
$scope.dcrlocked = result.dcrlocked;
$scope.leaves = result.leaves;
console.log(result.holidays);
//$scope.holidays = result.holidays;
for(i=0;i<result.holidays.length;i++)
{
holidays.push(new Date(result.holidays[i].date.replace(/-/g,',')));
}
alert(holidays.length);
return result.holidays;
});
promise.then(function(result) {
alert("holiday length after service post"+holidays.length);
$scope.dayClass = function(date, mode) {
if (mode === 'day') {
var dateToCheck = new Date(date);
for(var i = 0; i < holidays.length ; i++) {
if(areDatesEqual(holidays[i], dateToCheck)){
return 'appointment';
}
}
}
return '';
};
});
$rootScope.dt = new Date();
};
$scope.today();
$scope.clear = function() {
$rootScope.dt = null;
};
$scope.inlineOptions = {
minDate: new Date(),
showWeeks: false
};
$scope.dateOptions = {
formatYear: 'yy',
maxDate: new Date(2020, 5, 22),
minDate: new Date(),
startingDay: 1
};
// Disable weekend selection
function disabledasda(data) {
var date = data.date,
mode = data.mode;
return mode === 'day' && (date.getDay() === 0 || date.getDay() === 6);
}
$scope.toggleMin = function() {
$scope.inlineOptions.minDate = $scope.inlineOptions.minDate ? null : new Date();
$scope.dateOptions.minDate = $scope.inlineOptions.minDate;
};
$scope.toggleMin();
$scope.open1 = function() {
$scope.popup1.opened = true;
};
$scope.setDate = function(year, month, day) {
$rootScope.dt = new Date(year, month, day);
};
$scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
$scope.format = $scope.formats[0];
$scope.altInputFormats = ['M!/d!/yyyy'];
$scope.popup1 = {
opened: false
};
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
var afterTomorrow = new Date();
afterTomorrow.setDate(tomorrow.getDate() + 1);
$scope.events = [
{
date: tomorrow,
status: 'full'
},
{
date: afterTomorrow,
status: 'partially'
}
];
$scope.enableRequired = function(date, mode){
$scope.holidaysdateshardcoded = [
new Date(2016,04,03),
new Date(2016,04,08),
//new Date(2016,2,16),
new Date()
]
var isHoliday = true;
for(var i = 0; i < $scope.holidaysdateshardcoded.length ; i++) {
if(areDatesEqual($scope.holidaysdateshardcoded[i], date)){
isHoliday = false;
}
}
return ( mode === 'day' && isHoliday );
};
function areDatesEqual(date1, date2) {
return date1.setHours(0,0,0,0) === date2.setHours(0,0,0,0)
}
$scope.dateSelected = function(){
var appointments = [
new Date(2016,04,03),
new Date(2016,04,08),
new Date(),
];
var dateSelected = new Date($rootScope.dt);
for(var i = 0; i < appointments.length ; i++) {
if(areDatesEqual(appointments[i], dateSelected)){
performAction();
}
}
};
function performAction(){
location.href='#/data';
}
any help would be appreciated! please ask if confused!

Related

How to push date from calendar into startAt() function in angularJS

angular.module('...', ['...'])
.controller('main', main);
function main($scope, $firebaseArray) {
$scope.assign = function() {
$scope.assigned = $scope.deviceName;
};
$scope.today = function () {
// must put to set hours before isostring
$scope.dth = new Date();
$scope.test = moment($scope.dth).format('YYYY-MM-DD');
console.log($scope.test);
// this console.log is to check if the date format is correct
};
$scope.today();
$scope.inlineOptions = {
customClass: getDayClass,
minDate: new Date(),
showWeeks: true
};
$scope.open1 = function () {
$scope.popup1.opened = true;
};
$scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
$scope.format = $scope.formats[0];
$scope.altInputFormats = ['M!/d!/yyyy'];
$scope.popup1 = {
opened: false
};
$scope.dateOptionsM = {
formatYear: 'MM',
startingDay: 1,
minDate: new Date(2018, 0, 1, 0, 0, 0, 0),
minMode: 'month'
};
$scope.dateOptionsY = {
formatYear: 'yyyy',
startingDay: 1,
// minDate: start from which date
minDate: new Date(2018, 0, 1, 0, 0, 0, 0),
minMode: 'year'
};
function getDayClass(data) {
var date = data.date,
mode = data.mode;
if (mode === 'day') {
var dayToCheck = new Date(date).setHours(0, 0, 0, 0);
for (var i = 0; i < $scope.events.length; i++) {
var currentDay = new Date($scope.events[i].date).setHours(0, 0, 0, 0);
if (dayToCheck === currentDay) {
return $scope.events[i].status;
}
}
}
return '';
}
$scope.$watch('[assigned, test]', function(values) {
//UI for calendar function
var newtest = values[1];
var value = values[0];
var newRef = firebase.database().ref('editedData').child(value);
var hourRef = newRef.child('H');
$scope.halfhourlyData = $firebaseArray(hourRef.orderByChild('timestamp').limitToLast(48).startAt(newtest));
console.log(newtest);
// this console log only displays once
$scope.halfhourlyData.$loaded();
So what I want to do is to push the date that is set on the calendar into the startAt() function. However, upon testing, I realized that both logs only have been displayed once. Meaning that the value is not changing. However, on the HTML page the value does change and it uses $scope.dth. Is there a way for me to make the values change according to the calendar display? I'm using angular-bootstrap UI. Thanks!

How to handle tab hiding on load and loading content on demand via server call using angular material?

API's used : Angularjs, Angular material for tabs and ui-grid(ui-grid.info)
I have five tabs, currently i am loading all the five tabs using angular material with content as grid from angular-ui-grid; data loaded from backend using external pagination per page data from backend.
HTML Code:
<div cg-busy="{promise:downloadCSVPromise,message:'Downloading...'}">
<div cg-busy="{promise:loadingData,message:'Loading Data...'}">
<section style="min-height: 434px;" class="wrap">
<div ng-cloak>
<md-content>
<md-tabs md-selected="selectedIndex" md-border-bottom md-autoselect md-dynamic-height>
<md-tab id="tab1" ng-disabled="disableParts">
<md-tab-label>Tab 1</md-tab-label>
<md-tab-body>
<div class="custom-csv-link-location"></div>
<div ui-grid="gridOptions" ui-grid-pagination ui-grid-selection ui-grid-exporter ui-grid-auto-resize class="myGrid">
<div class="grid-msg-overlay" ng-hide="!vm.loading">
<div class="msg">
<span>
Loading Data...
<i class="fa fa-spinner fa-spin"></i>
</span>
</div>
</div>
<div class="watermark" ng-show="!gridOptions.data.length">No data available</div>
</div>
</md-tab-body>
</md-tab>
<md-tab id="tab2" ng-disabled="disableService">
<md-tab-label>Service Order</md-tab-label>
<md-tab-body>
<div ui-grid="serviceOrderGridOptions" ui-grid-pagination ui-grid-selection ui-grid-exporter class="myGrid">
<div class="watermark" ng-show="!serviceOrderGridOptions.data.length">No data available</div>
</div>
</md-tab-body>
</md-tab>
<md-tab id="tab3" ng-disabled="disableSales">
<md-tab-label>Sales Order</md-tab-label>
<md-tab-body>
<div ui-grid="salesGridOptions" ui-grid-pagination ui-grid-selection ui-grid-exporter class="myGrid">
<div class="watermark" ng-show="!salesGridOptions.data.length">No data available</div>
</div>
</md-tab-body>
</md-tab>
<md-tab id="tab4" ng-disabled="disableNC">
<md-tab-label>Non Conformances</md-tab-label>
<md-tab-body>
<div ui-grid="nonconfGridOptions" ui-grid-pagination ui-grid-selection ui-grid-exporter class="myGrid">
<div class="watermark" ng-show="!nonconfGridOptions.data.length">No data available</div>
</div>
</md-tab-body>
</md-tab>
<md-tab id="tab5" ng-disabled="disableBOM" md-on-select="resize()">
<md-tab-label>System BOM</md-tab-label>
<md-tab-body>
<div id="bom-charts">
<div class="chartBx bom-pie-chart">
<nvd3 options="pie_options" data="pie_data"></nvd3>
</div>
<div class="chartBx bom-stack-chart">
<nvd3 options="stack_options" data="stack_data"></nvd3>
</div>
<div class="clearfix"></div>
</div>
<div ui-grid="bomGridOptions" ui-grid-pagination ui-grid-selection ui-grid-exporter class="myGrid">
<div class="watermark" ng-show="!bomGridOptions.data.length">No data available</div>
</div>
</md-tab-body>
</md-tab>
</md-tabs>
</md-content>
</div>
</section>
</div>
</div>
Script Code:
function partsData(type) {
$scope.serversideFilters = [];
$scope.type=type ? type : "";
var paginationOptions = {
pageNumber: 1,
pageSize: 25,
sort: null
};
var originatorEv;
$scope.openMenu = function ($mdOpenMenu, ev) {
originatorEv = ev;
$mdOpenMenu(ev);
};
$scope.switchTabs = function (row, type) {
console.log('Menu item clicked - ' + row.entity.materialnum);
if(type === "service_order"){
$scope.selectedIndex = 1;
$scope.drillKeyword = row.entity.materialnum;
serviceOrderData('drill');
} else if(type === "sales_order"){
$scope.selectedIndex = 2;
$scope.drillKeyword = row.entity.materialnum;
salesData('drill');
} else if(type === "NC"){
$scope.selectedIndex = 3;
$scope.drillKeyword = row.entity.materialnum;
nonconfData('drill');
} else if(type === "BOM"){
$scope.selectedIndex = 4;
$scope.drillKeyword = row.entity.materialnum;
bomData('drill');
}
};
var fileNm = 'Parts_' + today + '.csv';
$scope.gridOptions = {
enableSelectAll: false,
enableRowSelection: false,
enableRowHeaderSelection: false,
exporterCsvFilename: fileNm,
exporterMenuPdf: false,
enableFiltering: true,
showGridFooter: true,
paginationPageSizes: [25, 50, 75],
paginationPageSize: 25,
useExternalPagination: true,
enableGridMenu: true,
columnDefs: [
{
name: 'materialnum', displayName: 'Part Number', cellClass: '', headerCellClass:'header-server-filtered',enableFiltering: false,width: 150,
cellTemplate: "<div class='ui-grid-cell-contents'><md-menu md-offset='0 45' md-position-mode='target target'><md-button class='md-icon-button' ng-click='grid.appScope.openMenu($mdOpenMenu, $event)'><i class='fa fa-indent'></i></md-button><md-menu-content width='2'><md-menu-item><md-button ng-click='grid.appScope.switchTabs(row,&apos;service_order&apos;)'>Service Order </md-button></md-menu-item><md-menu-item><md-button ng-click='grid.appScope.switchTabs(row,&apos;sales_order&apos;)'>Sales Order</md-button></md-menu-item><md-menu-item><md-button ng-click='grid.appScope.switchTabs(row,&apos;NC&apos;)'>Non Conformances</md-button></md-menu-item><md-menu-item><md-button ng-click='grid.appScope.switchTabs(row,&apos;BOM&apos;)'>System BOM</md-button></md-menu-item></md-menu-content></md-menu><span title='{{COL_FIELD CUSTOM_FILTERS}}' ng-click='grid.appScope.showAdvanced($event, row, col)' class='partNum'>{{COL_FIELD CUSTOM_FILTERS}}</span></div>"
},
{
name: 'materialdesc', displayName: 'Part Description', headerCellClass: 'header-server-filtered', width: 200,
filter: {
condition: $scope.filterPartDesc
},
cellTemplate: '<div ng-if="row.entity.materialdesc" title="{{row.entity.materialdesc}}" >{{row.entity.materialdesc}}</div><div ng-if="!row.entity.materialdesc"></div>',
},
sparableColumn,
consumableColumn,
cvvColumn,
npiColumn,
criticalColumn,
trColumn,
ipColumn,
faiColumn,
altpartsColumn,
repariableColumn,
{
name: 'onhandstock', displayName: 'On Hand Stock', headerCellClass: $scope.highlightFilteredHeader, enableFiltering: false,
cellTemplate: '<div ng-if="row.entity.onhandstock" class="tcenter">{{row.entity.onhandstock}}</div><div ng-if="!row.entity.onhandstock"></div>'
},
{
name: 'totalstock', displayName: 'Total Stock Limit', headerCellClass: $scope.highlightFilteredHeader, enableFiltering: false,
cellTemplate: '<div ng-if="row.entity.totalstock" class="tcenter">{{row.entity.totalstock}}</div><div ng-if="!row.entity.totalstock"></div>'
}
],
onRegisterApi: function (gridApi) {
$scope.gridApi = gridApi;
/* Facet filter for server side filtering*/
$scope.gridApi.core.on.filterChanged( $scope, function() {
var grid = this.grid;
$scope.serversideFilters = [];
angular.forEach(grid.columns, function(value, key) {
if(value.filters[0].term) {
var dummy = {};
console.log('FILTER TERM FOR ' + value.colDef.name + ' = ' + value.filters[0].term);
dummy['k'] = value.colDef.name;
dummy['v'] = value.filters[0].term;
$scope.serversideFilters.push(dummy);
}
});
getPage();
});
$scope.gridApi.core.on.sortChanged($scope, function (grid, sortColumns) {
if (sortColumns.length === 0) {
paginationOptions.sort = null;
} else {
paginationOptions.sort = sortColumns[0].sort.direction;
}
getPage();
});
$scope.gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
paginationOptions.pageNumber = newPage;
paginationOptions.pageSize = pageSize;
getPage();
});
}
}
$scope.filterPartDesc = function(searchTerm, callValue){
console.log('Inside Filter Part Description' +searchTerm );
if(value.filters[0].term) {
var dummy = {};
console.log('FILTER TERM FOR ' + value.colDef.name + ' = ' + value.filters[0].term);
dummy['k'] = value.colDef.name;
dummy['v'] = value.filters[0].term;
$scope.serversideFilters.push(dummy);
}
};
var getPage = function () {
var url = "http://test.server.com:8080/Dash/TestServlet";
var keyword = $scope.keyword ? $scope.keyword : '';
var paramsObj = {};
if($scope.type == "drill"){
keyword = $scope.drillKeyword;
paramsObj['ftype'] = 'exact';
}
paramsObj['query'] = keyword;
paramsObj['start'] = paginationOptions.pageSize * paginationOptions.pageNumber - paginationOptions.pageSize;
paramsObj['rows'] = paginationOptions.pageSize;
if (type && type !== '') {
if (type === 'cvv')
paramsObj[type] = 'YES';
if (type === 'sparable')
paramsObj[type] = 'YES';
if (type === 'consumable')
paramsObj[type] = 'C';
}
angular.forEach($scope.serversideFilters, function(obj){
paramsObj[obj.k] = obj.v;
});
$scope.loadingData = $http.get(url, { params: paramsObj, headers: { 'Content-Type': 'application/json' } })
.then(function (res) {
$scope.gridOptions.totalItems = res.data.numFound;
$scope.gridApi.grid.options.totalItems = res.data.numFound;
$scope.numFound = res.data.numFound;
var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
$scope.filters = res.data.facetFieldsMap;
var dummy = {
label: "",
value: ""
}
$scope.consumableFilter = [];
$scope.sparableFilter = [];
$scope.cvvFilter = [];
$scope.npiFilter = [];
$scope.criticalFilter = [];
$scope.trFilter = [];
$scope.ipFilter = [];
$scope.faiFilter = [];
$scope.altpartsFilter = [];
$scope.repariableFilter = [];
angular.forEach($scope.filters, function (ukey, uvalue) {
if (uvalue === "sparable") {
angular.forEach(ukey, function (key, value) {
dummy = {};
dummy.label = value;
dummy.value = value;
$scope.sparableFilter.push(dummy);
});
}
if (uvalue === "consumable") {
angular.forEach(ukey, function (key, value) {
/*if (value === 'N'){
value = 'NO';
}
if (value === 'Y'){
value = 'YES';
} */
dummy = {};
dummy.label = value;
dummy.value = value;
$scope.consumableFilter.push(dummy);
});
}
if (uvalue === "cvv") {
angular.forEach(ukey, function (key, value) {
dummy = {};
dummy.label = value;
dummy.value = value;
$scope.cvvFilter.push(dummy);
});
}
if (uvalue === "npi") {
angular.forEach(ukey, function (key, value) {
dummy = {};
dummy.label = value;
dummy.value = value;
$scope.npiFilter.push(dummy);
});
}
if (uvalue === "crtclpart") {
angular.forEach(ukey, function (key, value) {
dummy = {};
/*if (value === 'N'){
value = 'NO';
}
if (value === 'Y'){
value = 'YES';
} */
dummy.label = value;
dummy.value = value;
$scope.criticalFilter.push(dummy);
});
}
if (uvalue === "traderstrctd") {
angular.forEach(ukey, function (key, value) {
dummy = {};
dummy.label = value;
dummy.value = value;
$scope.trFilter.push(dummy);
});
}
if (uvalue === "ipsnstv") {
angular.forEach(ukey, function (key, value) {
dummy = {};
dummy.label = value;
dummy.value = value;
$scope.ipFilter.push(dummy);
});
}
if (uvalue === "fai") {
angular.forEach(ukey, function (key, value) {
dummy = {};
dummy.label = value;
dummy.value = value;
$scope.faiFilter.push(dummy);
});
}
if (uvalue === "alternatepart") {
angular.forEach(ukey, function (key, value) {
dummy = {};
dummy.label = value;
dummy.value = value;
$scope.altpartsFilter.push(dummy);
});
}
if (uvalue === "reprblcd") {
angular.forEach(ukey, function (key, value) {
dummy = {};
dummy.label = value;
dummy.value = value;
$scope.repariableFilter.push(dummy);
});
}
});
sparableColumn.filter.selectOptions = $scope.sparableFilter;
consumableColumn.filter.selectOptions = $scope.consumableFilter;
cvvColumn.filter.selectOptions = $scope.cvvFilter;
npiColumn.filter.selectOptions = $scope.npiFilter;
criticalColumn.filter.selectOptions = $scope.criticalFilter;
trColumn.filter.selectOptions = $scope.trFilter;
ipColumn.filter.selectOptions = $scope.ipFilter;
faiColumn.filter.selectOptions = $scope.faiFilter;
altpartsColumn.filter.selectOptions = $scope.altpartsFilter;
repariableColumn.filter.selectOptions = $scope.repariableFilter;
$scope.gridOptions.data = res.data.partSearchList;
if ($scope.gridOptions.data.length === 0) {
$scope.gridOptions.enablePaginationControls = false;
}
});
};
$scope.toggleFilterRow = function () {
$scope.gridOptions.enableFiltering = !$scope.gridOptions.enableFiltering;
$scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.COLUMN);
};
getPage();
}
Currently i am loading all the tabs with all the hits going to backend to fetch data but as per the requirement i need to change like below:
Only one tab will be loaded as per user selects in a dropdown to load the data and then inside the loaded tab we have links to other tab which will dynamically load the remaining tab/s on demand
I tried to hide or disable the material tabs but was getting error on load of the page on below lines :
$scope.gridApi.grid.options.totalItems = res.data.numFound;
I kept the loading of particular tab conditionally but then the HTML had the gridOptions defined and script was not initialized with the gridOptions it also threw error.
Finally i had tried below as well but didnt worked out.
$scope.serviceOrderGridOptions = {};
$scope.gridOptions = [];
$scope.serviceOrderGridOptions.data = [];
How can we make a tab load on demand with no issues on load of the page and also how to load the ui-grid inside it.
Appreciate your help!

Disable Dates Using Bootstrap datepicker

I am trying to disable some dates (eventually via an array I provide) using the datepicker control. However, it seems that nothing useful is passed in to the dateDisabled function. When I set a breakpoint in the developer tools, the first variable (which is set to data in the documentation examples) comes across as simply the number zero.
I have verified that the option itself works, as blankly returning a true disables all dates. What must I do to get valid inputs?
Note: I just discovered we are using angular-ui-bootstrap version 0.12.1.
JS
//options object for the datepicker control
$scope.dateOptions = {
dateDisabled: disableDates,
formatYear: "yyyy"
};
// Disable weekend selection
function disableDates(date, mode) {
//return mode === 'day' && (date.getDay() === 5 || date.getDay() === 6);
//return true;
return date === new Date(2016, 6, 18);
}
//Set the calendar open
$scope.openCalendar = function (e) {
e.preventDefault();
e.stopPropagation();
$scope.vm.is_cal_open = !$scope.vm.is_cal_open;
};
$scope.hasInvalidErrorDate = function (date) {
if (!date || date <= Date.parse("1/1/1900")) {
return true;
}
return false;
};
$scope.earliestErrorDate = Date.parse("1/1/1900");
HTML
<div class="col-sm-4">
<!-- Error Date -->
<div class="form-group" ng-class="{'has-error': hasInvalidErrorDate(vm.data.adjustment.error_date) && form.$dirty}">
<label for="error_date">Error Date</label>
<p class="input-group calendar-wrapper">
<!--input disabled the input so that it forces users to use the date picker and therfore ensure good input-->
<input type="text" datepicker-popup="MM/dd/yyyy"
title="Click the calendar button"
name="error_date"
datepicker-options="dateOptions"
class="form-control"
is-open="vm.is_cal_open"
width="5"
ng-disabled="true"
ng-model="vm.data.adjustment.error_date"
min-date="dateOptions.minDate" />
<span class="input-group-btn">
<button type="button" class="btn btn-default delegate-cal-btn" ng-click="openCalendar($event)"><i class="fa fa-calendar"></i></button>
</span>
</p>
<span class="text-danger small" ng-show="hasInvalidErrorDate(vm.data.adjustment.error_date) && form.$dirty">
Please select an error date
</span>
</div>
</div>
Working absolutely fine.
$scope.today = function() {
$scope.dt = new Date();
};
$scope.today();
$scope.clear = function() {
$scope.dt = null;
};
$scope.inlineOptions = {
customClass : getDayClass,
minDate : new Date(),
showWeeks : true
};
$scope.dateOptions = {
formatYear : 'yy',
maxDate : new Date(2199, 12, 31),
minDate : new Date(),
startingDay : 1
};
$scope.toggleMin = function() {
$scope.inlineOptions.minDate = $scope.inlineOptions.minDate ? null
: new Date();
$scope.dateOptions.minDate = $scope.inlineOptions.minDate;
};
$scope.toggleMin();
$scope.open1 = function() {
$scope.popup1.opened = true;
};
/*
* $scope.open2 = function() { $scope.popup2.opened =
* true; };
*/
$scope.setDate = function(year, month, day) {
$scope.dt = new Date(year, month, day);
};
$scope.formats = [ 'dd-MMMM-yyyy', 'yyyy/MM/dd',
'dd.MM.yyyy', 'shortDate' ];
$scope.format = $scope.formats[0];
$scope.altInputFormats = [ 'M!/d!/yyyy' ];
$scope.popup1 = {
opened : false
};
$scope.dateOptions = {
dateDisabled: disabled,
formatYear: 'yy',
maxDate: new Date(2020, 5, 22),
minDate: new Date(),
startingDay: 1
};
// Disable weekend selection
function disabled(data) {
var date = data.date,
mode = data.mode;
return mode === 'day' && (date.getDay() === 0 || date.getDay() === 6);
}
/*
* $scope.popup2 = { opened : false };
*/
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
var afterTomorrow = new Date();
afterTomorrow.setDate(tomorrow.getDate() + 1);
$scope.events = [ {
date : tomorrow,
status : 'full'
}, {
date : afterTomorrow,
status : 'partially'
} ];
function getDayClass(data) {
var date = data.date, mode = data.mode;
if (mode === 'day') {
var dayToCheck = new Date(date).setHours(0,
0, 0, 0);
for (var i = 0; i < $scope.events.length; i++) {
var currentDay = new Date(
$scope.events[i].date)
.setHours(0, 0, 0, 0);
if (dayToCheck === currentDay) {
return $scope.events[i].status;
}
}
}
return '';
}

Exporting Rally grid information to CSV

I am trying to export rally grid data to csv. Here's my code:
Ext.define('CustomApp', {
extend: 'Rally.app.App',
componentCls: 'app',
items:[{ xtype: 'container', itemId: 'print_button_box', padding: 5},{xtype: 'container', itemId: 'grid_box'}],
count: 0,
globalStore: null,
launch: function() {
this.globalStore = null;
this.count = 0;
this._addPrintButton();
list = [];
//Write app code here
this._get_stories_of_feature();
},
_addPrintButton: function() {
var me = this;
this.down('#print_button_box').add( {
xtype: 'rallybutton',
itemId: 'print_button',
text: 'CSV',
disabled: false,
handler: function() {
console.log('globalStore ',me.globalStore);
me._onClickExport();
}
});
},
_onClickExport: function () { //using this function to export to csv
if (document.getElementById('grid_box')) {
//Ext.getBody().mask('Exporting Tasks...');
console.log('inside export');
setTimeout(function () {
var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-' +
'microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head>' +
'<!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>' +
'{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>' +
'</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}' +
'</table></body></html>';
var base64 = function (s) {
return window.btoa(unescape(encodeURIComponent(s)));
};
var format = function (s, c) {
return s.replace(/{(\w+)}/g, function (m, p) {
return c[p];
});
};
var table = document.getElementById('grid_box');
console.log("Exporting table ",table);
var excel_data = '<tr>';
Ext.Array.each(table.innerHTML.match(/<span .*?x-column-header-text.*?>.*?<\/span>/gm), function (column_header_span) {
excel_data += (column_header_span.replace(/span/g, 'td'));
});
excel_data += '</tr>';
Ext.Array.each(table.innerHTML.match(/<tr class="x-grid-row.*?<\/tr>/gm), function (line) {
excel_data += line.replace(/[^\011\012\015\040-\177]/g, '>>');
});
console.log("Excel data ",excel_data);
var ctx = {worksheet: name || 'Worksheet', table: excel_data};
window.location.href = 'data:application/vnd.ms-excel;base64,' + base64(format(template, ctx));
Ext.getBody().unmask();
}, 500);
}else{
console.log("grid_box does not exist");
}
},
_createStore: function(){
var me = this;
//var f = [{property: 'UserStories', operator: '!=', value: null}];
Ext.create('Rally.data.WsapiDataStore',{
autoLoad: true,
model: "PortfolioItem/Feature",
limit: 5000,
fetch: ['FormattedID','Name','UserStories','c_DIteration','c_DPSI'],
listeners:{
load: function(store,data,success){
console.log("Store ",store);
var data_length = data.length;
console.log('Data length is '+data.length);
Ext.Array.each(data,function(item){
if(item.get('UserStories')==null){
store.remove(item);
}else{
var data = {
id: item.get("FormattedID"),
name: item.get("Name"),
UserStories: item.get("UserStories")._type,
DIteration: item.get("c_DIteration"),
DPSI: item.get("c_DPSI")
};
//list.push(data);
}
me._get_stories_of_feature(item.get("ObjectID"),item.get("Name"),data_length);
});
},
scope: this
}
});
},
_showGrid: function(store){
var me = this;
if(!this.grid){
this.grid = Ext.create('Rally.ui.grid.Grid',{
store: store,
columnCfgs:[
{text: 'Feature_ID', dataIndex: 'ide'},
{text: 'Feature Name', dataIndex: 'name'},
{text: 'Feature DIteration', dataInfex: 'fDIteration'},
{text: 'Story Name', dataIndex: 'UserStories'},
{text: 'Story ID', dataIndex: 'FormattedID'},
{text: 'Story DIteration', dataIndex: 'DIteration'},
{text: 'Story DPSI', dataIndex: 'DPSI'},
{text: 'Unscheduled', dataIndex: 'Unscheduled'}
]
});
me.globalStore = this.grid;
this.down('#grid_box').add(this.grid);
}
},
_get_stories_of_feature: function(){
var me = this;
Ext.create('Rally.data.WsapiDataStore',{
autoLoad: true,
model: "hierarchicalrequirement",
limit: 5000,
fetch: ['Name','ObjectID','FormattedID','Feature','c_DIteration','c_DPSI','DragAndDropRank'],
sorters:[{
property: 'DragAndDropRank', direction: 'ASC'
}],
filters:{
property: 'Feature', operator: '!=', value:null
},
listeners:{
load: function(store,data,success){
var data_length = data.length;
if(data_length>0){
console.log("Total stories ",data_length);
for(var i=0;i<data_length;i++){
var flag;
if(data[i].data.Feature.c_DIteration==null || data[i].data.Feature.c_DIteration.toString().indexOf("*")!=-1)
flag = "YES";
else flag = "NO";
var element = {
ide: data[i].data.Feature.FormattedID,
name: data[i].data.Feature.Name,
fDIteration: data[i].data.Feature.c_DIteration,
UserStories: data[i].data.Name,
FormattedID: data[i].data.FormattedID,
DIteration: data[i].data.c_DIteration,
DPSI: data[i].data.c_DPSI,
Unscheduled: flag
};
list.push(element);
console.log("me count is ",me.count);
console.log("Found ",data[i].data);
me.count++;
}
}
if(me.count==data_length){
console.log("Building store");
//once all the stories and feature data is computed
var myStore = Ext.create("Rally.data.custom.Store",{
data: list,
pageSize: 100
});
me._showGrid(myStore);
}
}
}
});
},
exportGrid: function(grid) {
if (Ext.isIE) {
this._ieToExcel(grid);
} else {
var data = this._getCSV(grid);
var a = document.createElement('a');
a.href = 'data:attachment/csv,' + data;
a.target ='_blank';
a.download = 'myFile.csv,' + encodeURIComponent(data); ;
a.innerHTML = "Click me to download the file.";
window.location = a;
}
},
_escapeForCSV: function(string) {
if (string.match(/,/)) {
if (!string.match(/"/)) {
string = '"' + string + '"';
} else {
string = string.replace(/,/g, ''); // comma's and quotes-- sorry, just loose the commas
}
}
return string;
},
_getFieldText: function(fieldData) {
var text;
if (fieldData == null || fieldData == undefined) {
text = '';
} else if (fieldData._refObjectName && !fieldData.getMonth) {
text = fieldData._refObjectName;
} else if (fieldData instanceof Date) {
text = Ext.Date.format(fieldData, this.dateFormat);
} else if (!fieldData.match) { // not a string or object we recognize...bank it out
text = '';
} else {
text = fieldData;
}
return text;
},
_getFieldTextAndEscape: function(fieldData) {
var string = this._getFieldText(fieldData);
return this._escapeForCSV(string);
},
_getCSV: function (grid) {
var cols = grid.columns;
var store = grid.store;
var data = '';
var that = this;
Ext.Array.each(cols, function(col, index) {
if (col.hidden != true) {
data += that._getFieldTextAndEscape(col.text) + ',';
}
});
data += "\n";
store.each(function(record) {
var entry = record.getData();
Ext.Array.each(cols, function(col, index) {
if (col.hidden != true) {
var fieldName = col.dataIndex;
var text = entry[fieldName];
data += that._getFieldTextAndEscape(text) + ',';
}
});
data += "\n";
});
return data;
},
_ieGetGridData : function(grid, sheet) {
var that = this;
var resourceItems = grid.store.data.items;
var cols = grid.columns;
Ext.Array.each(cols, function(col, colIndex) {
if (col.hidden != true) {
console.log('header: ', col.text);
sheet.cells(1,colIndex + 1).value = col.text;
}
});
var rowIndex = 2;
grid.store.each(function(record) {
var entry = record.getData();
Ext.Array.each(cols, function(col, colIndex) {
if (col.hidden != true) {
var fieldName = col.dataIndex;
var text = entry[fieldName];
var value = that._getFieldText(text);
sheet.cells(rowIndex, colIndex+1).value = value;
}
});
rowIndex++;
});
},
_ieToExcel: function (grid) {
if (window.ActiveXObject){
var xlApp, xlBook;
try {
xlApp = new ActiveXObject("Excel.Application");
xlBook = xlApp.Workbooks.Add();
} catch (e) {
Ext.Msg.alert('Error', 'For the export to work in IE, you have to enable a security setting called "Initialize and script ActiveX control not marked as safe" from Internet Options -> Security -> Custom level..."');
return;
}
xlBook.worksheets("Sheet1").activate;
var XlSheet = xlBook.activeSheet;
xlApp.visible = true;
this._ieGetGridData(grid, XlSheet);
XlSheet.columns.autofit;
}
}
});
I am using the "_onClickExport" function that I read about here to export my grid data to CSV but when I execute that function, it can't find ElementId "grid_box", although I have defined it.
I was able to export with your code after making these changes:
line 31, change to
if (this.down('#grid_box')){
line 52, change to
var table = that.getComponent('grid_box');
where that is defined on the top of _onClickExport
var that = this;
line 57, and a similar line below it, replace table.innerHTML.match with table.getEl().dom.outerHTML.match
Ext.Array.each(table.getEl().dom.outerHTML.match

Loading grid only after "all" the data stores have loaded

I have this code that loads a data store for all stories that contain each of the names from an array.
var prefix_set = [list of names]
for(var i=0;i<prefix_set.length;i++)
_get_stories_of_feature(prefix_set[i]) //this function creates a data store
I am storing all the data into a global array and creating a data store which is passed to a grid in the end. The problem is that my grid loads up with incomplete data (the grid loads up even before all the data has been loaded into the global array).
Here's my code:
Ext.define('CustomApp', {
extend: 'Rally.app.App',
componentCls: 'app',
items:[{ xtype: 'container', itemId: 'print_button_box', padding: 5},{xtype: 'container', itemId: 'grid_box'}],
count: 0,
globalStore: null,
totalDataLength: 0,
gridCounter: 0,
launch: function() {
var me = this;
this.globalStore = null;
this.gridCounter = 0;
this.totalDataLength=0;
this.count = 0;
this._addPrintButton();
list = [];
//Write app code here
var prefix_set = ["Epic:","Arch:","Refa:","Innov:","Spike:","Producer:","Dependency:","Consumer:"];
var i;
for(i=0;i<prefix_set.length;i++){
this._get_stories_of_feature(prefix_set[i],prefix_set.length,i);
}
},
_addPrintButton: function() {
var me = this;
this.down('#print_button_box').add( {
xtype: 'rallybutton',
itemId: 'print_button',
text: 'CSV',
disabled: false,
handler: function() {
console.log('globalStore ',me.globalStore);
me.exportGrid(me.globalStore);
}
});
},
_onClickExport: function () {
if (document.getElementById('grid_box')) {
//Ext.getBody().mask('Exporting Tasks...');
console.log('inside export');
setTimeout(function () {
var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-' +
'microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head>' +
'<!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>' +
'{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>' +
'</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}' +
'</table></body></html>';
var base64 = function (s) {
return window.btoa(unescape(encodeURIComponent(s)));
};
var format = function (s, c) {
return s.replace(/{(\w+)}/g, function (m, p) {
return c[p];
});
};
var table = document.getElementById('grid_box');
console.log("Exporting table ",table);
var excel_data = '<tr>';
Ext.Array.each(table.innerHTML.match(/<span .*?x-column-header-text.*?>.*?<\/span>/gm), function (column_header_span) {
excel_data += (column_header_span.replace(/span/g, 'td'));
});
excel_data += '</tr>';
Ext.Array.each(table.innerHTML.match(/<tr class="x-grid-row.*?<\/tr>/gm), function (line) {
excel_data += line.replace(/[^\011\012\015\040-\177]/g, '>>');
});
console.log("Excel data ",excel_data);
var ctx = {worksheet: name || 'Worksheet', table: excel_data};
window.location.href = 'data:application/vnd.ms-excel;base64,' + base64(format(template, ctx));
Ext.getBody().unmask();
}, 500);
}else{
console.log("grid_box does not exist");
}
},
tableToExcel: function(){
var me = this;
console.log("Global store ",me.globalStore);
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))); }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }); };
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table);
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML};
window.location.href = uri + base64(format(template, ctx));
};
},
_createStore: function(){
var me = this;
//var f = [{property: 'UserStories', operator: '!=', value: null}];
Ext.create('Rally.data.WsapiDataStore',{
autoLoad: true,
model: "PortfolioItem/Feature",
limit: 10000,
fetch: ['FormattedID','Name','UserStories','c_DIteration','c_DPSI'],
listeners:{
load: function(store,data,success){
console.log("Store ",store);
var data_length = data.length;
console.log('Data length is '+data.length);
Ext.Array.each(data,function(item){
if(item.get('UserStories')==null){
store.remove(item);
}else{
var data = {
id: item.get("FormattedID"),
name: item.get("Name"),
UserStories: item.get("UserStories")._type,
DIteration: item.get("c_DIteration"),
DPSI: item.get("c_DPSI")
};
//list.push(data);
}
me._get_stories_of_feature(item.get("ObjectID"),item.get("Name"),data_length);
});
},
scope: this
}
});
},
_showGrid: function(store){
var me = this;
if(!this.grid){
this.grid = Ext.create('Rally.ui.grid.Grid',{
store: store,
columnCfgs:[
{text: 'Feature', dataIndex: 'name'},
{text: 'FormattedID', dataIndex: 'FormattedID'},
{text: 'Name', dataIndex: 'UserStories'},
{text: 'Release', dataIndex: 'Release'},
{text: 'Iteration', dataIndex: 'Iteration'},
{text: 'DIteration', dataIndex: 'DIteration'},
{text: 'DPSI', dataIndex: 'DPSI'},
{text: 'Schedule State', dataIndex: 'ScheduleState'},
{text: 'Task Remaining Total', dataIndex: 'TaskRemainingTotal'},
{text: 'Owner', dataIndex: 'Owner'},,
{text: 'Project', dataIndex: 'Project'},
{text: 'Unscheduled', dataIndex: 'Unscheduled'}
]
});
me.globalStore = this.grid;
this.down('#grid_box').add(this.grid);
}
},
_get_stories_of_feature: function(name,length,k){
var me = this;
Ext.create('Rally.data.WsapiDataStore',{
autoLoad: true,
model: "HierarchicalRequirement",
limit: 10000,
fetch: ['Name','ObjectID','FormattedID','Parent','Feature','TaskRemainingTotal','c_DIteration','c_DPSI','DragAndDropRank','Release','Iteration','Project','Owner','ScheduleState'],
sorters:[{
property: 'DragAndDropRank', direction: 'ASC'
,},{property: 'Project', direction: 'ASC'}],
filters:[{
property: 'Name', operator: 'contains', value: name
},{
property: 'ScheduleState', operator: '!=', value: 'Accepted'
}],
pageSize: 5000,
listeners:{
load: function(store,data,success){
var data_length = data.length;
if(data_length>0){
console.log("Total stories ",data_length);
for(var i=0;i<data_length;i++){
console.log("Data length for ",k," is ",data_length);
console.log("Data i ",data[i]);
me.totalDataLength++;
var flag;
var iteration=""; var release="";
var fid = "",fname="";
var owner="";
if(data[i].data.Feature!=null && (data[i].data.Feature.c_DIteration==null || data[i].data.Feature.c_DIteration.toString().indexOf("*")!=-1))
flag = "YES";
else flag = "NO";
if(data[i].data.Iteration!=null){
iteration = data[i].data.Iteration._refObjectName;
}
if(data[i].data.Release!=null){
release = data[i].data.Release._refObjectName;
}
if(data[i].data.Owner!=null){
owner = data[i].data.Owner._refObjectName;
}
if(data[i].data.Feature!=null){
fid = data[i].data.Feature.FormattedID;
fname = data[i].data.Feature.Name;
}
var element = {
name: fid+":"+fname,
UserStories: data[i].data.Name,
Project: data[i].data.Project._refObjectName,
Owner: owner,
FormattedID: data[i].data.FormattedID,
Iteration: iteration,
TaskRemainingTotal: parseInt(data[i].data.TaskRemainingTotal),
Release: release,
ScheduleState: data[i].data.ScheduleState,
DIteration: data[i].data.c_DIteration,
DPSI: data[i].data.c_DPSI,
Unscheduled: flag
};
list.push(element);
console.log("me count is ",me.count);
console.log("Found ",data[i].data);
me.count++;
}
}
console.log("Total Data Length is ",me.totalDataLength);
console.log("k is ",k," and length is ",length);
if(k==length-1){
console.log("Building store");
//once all the stories and feature data is computed
var myStore = Ext.create("Rally.data.custom.Store",{
data: list,
sortable: true,
pageSize: me.totalDataLength,
});
me._showGrid(myStore);
}
}
}
});
me.gridCounter++;
},
exportGrid: function(grid) {
if (Ext.isIE) {
this._ieToExcel(grid);
} else {
var data = this._getCSV(grid);
window.location = 'data:text/csv;charset=utf8,' + encodeURIComponent(data);
}
},
_escapeForCSV: function(string) {
if (string.match(/,/)) {
if (!string.match(/"/)) {
string = '"' + string + '"';
} else {
string = string.replace(/,/g, ''); // comma's and quotes-- sorry, just loose the commas
}
}
return string;
},
_getFieldText: function(fieldData) {
var text;
if (fieldData == null || fieldData == undefined) {
text = '';
} else if (fieldData._refObjectName && !fieldData.getMonth) {
text = fieldData._refObjectName;
} else if (fieldData instanceof Date) {
text = Ext.Date.format(fieldData, this.dateFormat);
} else if (!fieldData.match) { // not a string or object we recognize...bank it out
text = '';
} else {
text = fieldData;
}
return text;
},
_getFieldTextAndEscape: function(fieldData) {
var string = this._getFieldText(fieldData);
return this._escapeForCSV(string);
},
_getCSV: function (grid) {
var cols = grid.columns;
var store = grid.store;
var data = '';
console.log("Grid.Store is ",grid.store);
var that = this;
Ext.Array.each(cols, function(col, index) {
if (col.hidden != true) {
data += that._getFieldTextAndEscape(col.text) + ',';
}
});
data += "\n";
store.each(function(record) {
var entry = record.getData();
Ext.Array.each(cols, function(col, index) {
if (col.hidden != true) {
var fieldName = col.dataIndex;
var text = entry[fieldName];
data += that._getFieldTextAndEscape(text) + ',';
}
});
data += "\n";
});
return data;
},
_ieGetGridData : function(grid, sheet) {
var that = this;
var resourceItems = grid.store.data.items;
var cols = grid.columns;
Ext.Array.each(cols, function(col, colIndex) {
if (col.hidden != true) {
console.log('header: ', col.text);
sheet.cells(1,colIndex + 1).value = col.text;
}
});
var rowIndex = 2;
grid.store.each(function(record) {
var entry = record.getData();
Ext.Array.each(cols, function(col, colIndex) {
if (col.hidden != true) {
var fieldName = col.dataIndex;
var text = entry[fieldName];
var value = that._getFieldText(text);
sheet.cells(rowIndex, colIndex+1).value = value;
}
});
rowIndex++;
});
},
_ieToExcel: function (grid) {
if (window.ActiveXObject){
var xlApp, xlBook;
try {
xlApp = new ActiveXObject("Excel.Application");
xlBook = xlApp.Workbooks.Add();
} catch (e) {
Ext.Msg.alert('Error', 'For the export to work in IE, you have to enable a security setting called "Initialize and script ActiveX control not marked as safe" from Internet Options -> Security -> Custom level..."');
return;
}
xlBook.worksheets("Sheet1").activate;
var XlSheet = xlBook.activeSheet;
xlApp.visible = true;
this._ieGetGridData(grid, XlSheet);
XlSheet.columns.autofit;
}
}
});
Please take a look at the code in this post, where Mark uses promises, and builds three separate Rally.data.wsapi.Stores and only after all the data is there _makeGrid(resultArray) is called.

Resources