i'm using Angularjs NgTable, with pagination inside of a tab provided by Angularjs Material. this works fine. i've used it in many parts of my project and realoaded it many times in differents parts.
but in this case, i can't reload the tables. and don't know what is the problem or how shoud do the reload.
i have in DistribucionController this functions:
$scope.listaFacturaTierra = function () {
var idFactura = $stateParams.idFactura;
$facturaTierra = distribucionService.getStockTierra(idFactura);
$facturaTierra.then(function (datos) {
$scope.facturaTierra = datos.data;
var data = datos;
$scope.tableFacturaTierra = new NgTableParams({
page: 1,
count: 8
}, {
total: data.length,
getData: function (params) {
data = $scope.facturaTierra;
params.total(data.length);
if (params.total() <= ((params.page() - 1) * params.count())) {
params.page(1);
}
return data.slice((params.page() - 1) * params.count(), params.page() * params.count());
}});
});
};
$scope.listaFacturaBebelandia = function () {
var idFactura = $stateParams.idFactura;
$facturaBebelandia = distribucionService.getStockBebelandia(idFactura);
$facturaBebelandia.then(function (datos) {
var data = datos.data;
$scope.facturaBebelandia = datos.data;
$scope.tableFacturaBebelandia = new NgTableParams({
page: 1,
count: 10
}, {
total: data.length,
getData: function (params) {
data = $scope.facturaBebelandia;
params.total(data.length);
if (params.total() <= ((params.page() - 1) * params.count())) {
params.page(1);
}
return data.slice((params.page() - 1) * params.count(), params.page() * params.count());
}});
});
};
$scope.listaFacturaLibertador = function () {
var idFactura = $stateParams.idFactura;
$facturaLibertador = distribucionService.getStockLibertador(idFactura);
$facturaLibertador.then(function (datos) {
var data = datos.data;
$scope.facturaLibertador = datos.data;
$scope.tableFacturaLibertador = new NgTableParams({
page: 1,
count: 10
}, {
total: data.length,
getData: function (params) {
data = $scope.facturaLibertador;
params.total(data.length);
if (params.total() <= ((params.page() - 1) * params.count())) {
params.page(1);
}
return data.slice((params.page() - 1) * params.count(), params.page() * params.count());
}});
});
};
they are displayed fine, and the pagination is working as well.
i add elements using Angularjs Material ngDialog using 3 functions the make the process.
Show the principal modal:
$scope.distribuirModal = function (producto) {
$rootScope.modalProducto = producto;
ngDialog.open({
template: 'views/modals/distribucion/modal-distribuir.html',
className: 'ngdialog-theme-advertencia',
showClose: false,
controller: 'DistribucionController',
closeByDocument: false,
closeByEscape: false
});
};
make the processs of the data, and show a modal of confirmation:
$scope.confirmarDistribuir = function (modalDistribuir) {
var control = 0;
control = modalDistribuir.tierra + modalDistribuir.bebelandia + modalDistribuir.libertador;
if (control === $rootScope.modalProducto.cantidadTotal) {
if (modalDistribuir.tierra !== null) {
$scope.wrapper.stockTierra.idProducto = $rootScope.modalProducto;
$scope.wrapper.stockTierra.cantidad = modalDistribuir.tierra;
}
if (modalDistribuir.bebelandia !== null) {
$scope.wrapper.stockBebelandia.idProducto = $rootScope.modalProducto;
$scope.wrapper.stockBebelandia.cantidad = modalDistribuir.bebelandia;
}
if (modalDistribuir.libertador !== null) {
$scope.wrapper.stockLibertador.idProducto = $rootScope.modalProducto;
$scope.wrapper.stockLibertador.cantidad = modalDistribuir.libertador;
}
ngDialog.open({
template: 'views/modals/distribucion/confirmacion-distribuir.html',
className: 'ngdialog-theme-advertencia',
showClose: false,
controller: 'DistribucionController',
closeByDocument: false,
closeByEscape: false,
data: {
'wrapper': $scope.wrapper,
'producto': $rootScope.modalProducto
}
});
} else {
$scope.alerts.push({
type: 'danger',
msg: 'La cantidad total de productos a distribuir debe ser igual a la cantidad total de productos en almacen.'
});
}
};
in this modal i execute a function that save the data on my API
$scope.finalizarDistribucion = function () {
$scope.sendWrapper = {
stockTierra: null,
stockBebelandia: null,
stockLibertador: null
};
if ($scope.ngDialogData.wrapper.stockTierra.idProducto !== null && $scope.ngDialogData.wrapper.stockTierra.cantidad) {
$scope.sendWrapper.stockTierra = $scope.ngDialogData.wrapper.stockTierra;
}
if ($scope.ngDialogData.wrapper.stockBebelandia.idProducto !== null && $scope.ngDialogData.wrapper.stockBebelandia.cantidad) {
$scope.sendWrapper.stockBebelandia = $scope.ngDialogData.wrapper.stockBebelandia;
}
if ($scope.ngDialogData.wrapper.stockLibertador.idProducto !== null && $scope.ngDialogData.wrapper.stockLibertador.cantidad) {
$scope.sendWrapper.stockLibertador = $scope.ngDialogData.wrapper.stockLibertador;
}
$distribute = distribucionService.add($scope.sendWrapper);
$distribute.then(function (datos) {
if (datos.status === 200) {
ngDialog.closeAll();
toaster.pop({
type: 'success',
title: 'Exito',
body: 'Se ha distribuido con exito los productos.',
showCloseButton: false
});
}
});
$scope.$emit('updateTables', $scope.ngDialogData.producto);
$scope.$emit('updateStock', {});
};
in this function i do two $emit
the first one update my object Producto in my ProductoController and send a $broadcast to update my principal table
$scope.$on('updateTables', function (event, object) {
var idFactura = parseInt($stateParams.idFactura);
object.estadoDistribucion = true;
$updateProducto = _productoService.update(object);
$updateProducto.then(function (datos) {
if (datos.status === 200) {
$rootScope.$broadcast('updateTableProducto', {'idFactura': idFactura});
}
});
});
this last works fine, reload the table without problems.
the second $emit is the problem, it must reload the another 3 tables
$scope.$on('updateStock', function () {
var idFactura = parseInt($stateParams.idFactura);
$facturaTierra = distribucionService.getStockTierra(idFactura);
$facturaTierra.then(function (datos) {
$scope.facturaTierra = datos.data;
$scope.tableFacturaTierra.reload();
});
$facturaBebelandia = distribucionService.getStockBebelandia(idFactura);
$facturaBebelandia.then(function (datos) {
$scope.facturaBebelandia = datos.data;
$scope.tableFacturaBebelandia.reload();
});
$facturaLibertador = distribucionService.getStockLibertador(idFactura);
$facturaLibertador.then(function (datos) {
$scope.facturaLibertador = datos.data;
$scope.tableFacturaLibertador.reload();
});
});
but my parameters of ngTable are undefined and the reload fails.
have somebody any idea what i'm doing wrong?
Finally after try many times i got the answer.
First in my ProductoController i did a $broadcast to my DistribucionController
$rootScope.$on('updateTableProducto', function (event, object) {
$list = _productoService.searchByIdFactura(object.idFactura);
$list.then(function (datos) {
$scope.productosFactura = datos.data;
$rootScope.$broadcast('updateStock', {});
$scope.tableProductosFactura.reload();
});
});
then on i receive this $broadcast on my another controller using
$scope.$on('updateStock', function (event, object) {
var idFactura = parseInt($stateParams.idFactura);
$facturaTierra = distribucionService.getStockTierra(idFactura);
$facturaTierra.then(function (datos) {
$scope.facturaTierra = datos.data;
$scope.tableFacturaTierra.reload();
});
$facturaBebelandia = distribucionService.getStockBebelandia(idFactura);
$facturaBebelandia.then(function (datos) {
$scope.facturaBebelandia = datos.data;
$scope.tableFacturaBebelandia.reload();
});
$facturaLibertador = distribucionService.getStockLibertador(idFactura);
$facturaLibertador.then(function (datos) {
$scope.facturaLibertador = datos.data;
$scope.tableFacturaLibertador.reload();
});
});
NOTE: if i write $rootScope.on it execute 3 times. so in $scope just make one loop.
I hope this will be helpul to someone.
Related
I'm working on odoo9,I have a date field in my model, I want to enable only Mondays in its calendar, I found Jquery solutions on google and applied to my date field but could not get the desired result. Instead I get two calendars , second one is shown when I continue to press left click on my date field.See second Image.
Second image.
This is my Jquery code:
$('.o_datepicker_input').datepicker({
beforeShowDay: function (date)
{
return [(date.getDay() == 1), ""];
},
});
try this
$(".week").datepicker("option", {
beforeShowDay: function (date)
{
return [date.getDay() == 1, ''];
}
});
var weekOptions = { "changeMonth": false, "changeYear": false, "stepMonths": 0,
beforeShowDay: function (date) {
return [date.getDay() == 1, ''];
}
};
$(function () {
$(".week").datepicker("option", weekOptions);
});
Here is the answer. Little bit tricky.
odoo.define('automation.saturday_datepicker', function (require) {
"use strict";
var core = require('web.core');
var formats = require('web.formats');
var time = require('web.time');
var Widget = require('web.Widget');
var _t = core._t;
`enter code here`var DateWidget = Widget.extend({
template: "web.datepicker",
type_of_date: "date",
events: {
'dp.change': 'change_datetime',
'dp.show': 'set_datetime_default',
'change .o_datepicker_input': 'change_datetime',
},
init: function(parent, options) {
this._super.apply(this, arguments);
var l10n = _t.database.parameters;
this.name = parent.name;
this.options = _.defaults(options || {}, {
pickTime: this.type_of_date === 'datetime',
useSeconds: this.type_of_date === 'datetime',
startDate: moment({ y: 1900 }),
endDate: moment().add(200, "y"),
calendarWeeks: true,
icons: {
time: 'fa fa-clock-o',
date: 'fa fa-calendar',
up: 'fa fa-chevron-up',
down: 'fa fa-chevron-down'
},
language : moment.locale(),
format : time.strftime_to_moment_format((this.type_of_date === 'datetime')? (l10n.date_format + ' ' + l10n.time_format) : l10n.date_format),
daysOfWeekDisabled: [0, 1,2,3,4,5],
});
},
start: function() {
this.$input = this.$('input.o_datepicker_input');
this.$el.datetimepicker(this.options);
this.picker = this.$el.data('DateTimePicker');
this.set_readonly(false);
this.set_value(false);
},
set_value: function(value) {
this.set({'value': value});
this.$input.val((value)? this.format_client(value) : '');
this.picker.setValue(this.format_client(value));
},
get_value: function() {
return this.get('value');
},
set_value_from_ui: function() {
var value = this.$input.val() || false;
this.set_value(this.parse_client(value));
},
set_readonly: function(readonly) {
this.readonly = readonly;
this.$input.prop('readonly', this.readonly);
},
is_valid: function() {
var value = this.$input.val();
if(value === "") {
return true;
} else {
try {
this.parse_client(value);
return true;
} catch(e) {
return false;
}
}
},
parse_client: function(v) {
return formats.parse_value(v, {"widget": this.type_of_date});
},
format_client: function(v) {
return formats.format_value(v, {"widget": this.type_of_date});
},
set_datetime_default: function() {
//when opening datetimepicker the date and time by default should be the one from
//the input field if any or the current day otherwise
var value = moment().second(0);
if(this.$input.val().length !== 0 && this.is_valid()) {
value = this.$input.val();
}
// temporarily set pickTime to true to bypass datetimepicker hiding on setValue
// see https://github.com/Eonasdan/bootstrap-datetimepicker/issues/603
var saved_picktime = this.picker.options.pickTime;
this.picker.options.pickTime = true;
this.picker.setValue(value);
this.picker.options.pickTime = saved_picktime;
},
change_datetime: function(e) {
if(this.is_valid()) {
this.set_value_from_ui();
this.trigger("datetime_changed");
}
},
commit_value: function() {
this.change_datetime();
},
destroy: function() {
this.picker.destroy();
this._super.apply(this, arguments);
},
});
var DateTimeWidget = DateWidget.extend({
type_of_date: "datetime"
});
return {
DateWidget: DateWidget,
DateTimeWidget: DateTimeWidget,
};
});
odoo.define('web.form_widgets_custom', function (require) {
"use strict";
var core = require('web.core');
var common = require('web.form_common');
var formats = require('web.formats');
var automation_saturday_date_picker = require('automation.saturday_datepicker')
var _t = core._t;
var QWeb = core.qweb;
var FieldDatetime = core.form_widget_registry.get('datetime')
var FieldDate = FieldDatetime.extend({
template: "FieldDate",
build_widget: function() {
return new automation_saturday_date_picker.DateWidget(this);
}
});
core.form_widget_registry
.add('saturday_date_widget', FieldDate)
});
And finally give widget="saturday_date_widget" to model's field in xml.
I'm seeking a solution for the toastr.js "error" that causes the webpage, if scrolled down, to jump up again when a new toastr is displayed
GitHub page containing the script
I've tried to change the top to auto, but that wasn't an accepted parameter, because nothing showed up then.
Isn't there any way to make it appear where the mouse is at the moment?
.toast-top-center {
top: 12px;
margin: 0 auto;
left: 43%;
}
this has the calling code:
<p><span style="font-family:'Roboto','One Open Sans', 'Helvetica Neue', Helvetica, sans-serif;color:rgb(253,253,255); font-size:16px ">
xxxxxxxxxxxxx
</span></p>
This is the function code:
<script type='text/javascript'> function playclip() {
toastr.options = {
"debug": false,
"positionClass": "toast-top-center",
"onclick": null,
"fadeIn": 800,
"fadeOut": 1000,
"timeOut": 5000,
"extendedTimeOut": 1000
}
toastr["error"]("This link is pointing to a page that hasn't been written yet,</ br> sorry for the inconvenience?"); } </script>
And this is the script itself:
/*
* Toastr
* Copyright 2012-2015
* Authors: John Papa, Hans Fjällemark, and Tim Ferrell.
* All Rights Reserved.
* Use, reproduction, distribution, and modification of this code is subject to the terms and
* conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php
*
* ARIA Support: Greta Krafsig
*
* Project: https://github.com/CodeSeven/toastr
*/
/* global define */
(function (define) {
define(['jquery'], function ($) {
return (function () {
var $container;
var listener;
var toastId = 0;
var toastType = {
error: 'error',
info: 'info',
success: 'success',
warning: 'warning'
};
var toastr = {
clear: clear,
remove: remove,
error: error,
getContainer: getContainer,
info: info,
options: {},
subscribe: subscribe,
success: success,
version: '2.1.3',
warning: warning
};
var previousToast;
return toastr;
////////////////
function error(message, title, optionsOverride) {
return notify({
type: toastType.error,
iconClass: getOptions().iconClasses.error,
message: message,
optionsOverride: optionsOverride,
title: title
});
}
function getContainer(options, create) {
if (!options) { options = getOptions(); }
$container = $('#' + options.containerId);
if ($container.length) {
return $container;
}
if (create) {
$container = createContainer(options);
}
return $container;
}
function info(message, title, optionsOverride) {
return notify({
type: toastType.info,
iconClass: getOptions().iconClasses.info,
message: message,
optionsOverride: optionsOverride,
title: title
});
}
function subscribe(callback) {
listener = callback;
}
function success(message, title, optionsOverride) {
return notify({
type: toastType.success,
iconClass: getOptions().iconClasses.success,
message: message,
optionsOverride: optionsOverride,
title: title
});
}
function warning(message, title, optionsOverride) {
return notify({
type: toastType.warning,
iconClass: getOptions().iconClasses.warning,
message: message,
optionsOverride: optionsOverride,
title: title
});
}
function clear($toastElement, clearOptions) {
var options = getOptions();
if (!$container) { getContainer(options); }
if (!clearToast($toastElement, options, clearOptions)) {
clearContainer(options);
}
}
function remove($toastElement) {
var options = getOptions();
if (!$container) { getContainer(options); }
if ($toastElement && $(':focus', $toastElement).length === 0) {
removeToast($toastElement);
return;
}
if ($container.children().length) {
$container.remove();
}
}
// internal functions
function clearContainer (options) {
var toastsToClear = $container.children();
for (var i = toastsToClear.length - 1; i >= 0; i--) {
clearToast($(toastsToClear[i]), options);
}
}
function clearToast ($toastElement, options, clearOptions) {
var force = clearOptions && clearOptions.force ? clearOptions.force : false;
if ($toastElement && (force || $(':focus', $toastElement).length === 0)) {
$toastElement[options.hideMethod]({
duration: options.hideDuration,
easing: options.hideEasing,
complete: function () { removeToast($toastElement); }
});
return true;
}
return false;
}
function createContainer(options) {
$container = $('<div/>')
.attr('id', options.containerId)
.addClass(options.positionClass);
$container.appendTo($(options.target));
return $container;
}
function getDefaults() {
return {
tapToDismiss: true,
toastClass: 'toast',
containerId: 'toast-container',
debug: false,
showMethod: 'fadeIn', //fadeIn, slideDown, and show are built into jQuery
showDuration: 300,
showEasing: 'swing', //swing and linear are built into jQuery
onShown: undefined,
hideMethod: 'fadeOut',
hideDuration: 1000,
hideEasing: 'swing',
onHidden: undefined,
closeMethod: false,
closeDuration: false,
closeEasing: false,
closeOnHover: true,
extendedTimeOut: 1000,
iconClasses: {
error: 'toast-error',
info: 'toast-info',
success: 'toast-success',
warning: 'toast-warning'
},
iconClass: 'toast-info',
positionClass: 'toast-top-right',
timeOut: 5000, // Set timeOut and extendedTimeOut to 0 to make it sticky
titleClass: 'toast-title',
messageClass: 'toast-message',
escapeHtml: false,
target: 'body',
closeHtml: '<button type="button">×</button>',
closeClass: 'toast-close-button',
newestOnTop: true,
preventDuplicates: false,
progressBar: false,
progressClass: 'toast-progress',
rtl: false
};
}
function publish(args) {
if (!listener) { return; }
listener(args);
}
function notify(map) {
var options = getOptions();
var iconClass = map.iconClass || options.iconClass;
if (typeof (map.optionsOverride) !== 'undefined') {
options = $.extend(options, map.optionsOverride);
iconClass = map.optionsOverride.iconClass || iconClass;
}
if (shouldExit(options, map)) { return; }
toastId++;
$container = getContainer(options, true);
var intervalId = null;
var $toastElement = $('<div/>');
var $titleElement = $('<div/>');
var $messageElement = $('<div/>');
var $progressElement = $('<div/>');
var $closeElement = $(options.closeHtml);
var progressBar = {
intervalId: null,
hideEta: null,
maxHideTime: null
};
var response = {
toastId: toastId,
state: 'visible',
startTime: new Date(),
options: options,
map: map
};
personalizeToast();
displayToast();
handleEvents();
publish(response);
if (options.debug && console) {
console.log(response);
}
return $toastElement;
function escapeHtml(source) {
if (source == null) {
source = '';
}
return source
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
function personalizeToast() {
setIcon();
setTitle();
setMessage();
setCloseButton();
setProgressBar();
setRTL();
setSequence();
setAria();
}
function setAria() {
var ariaValue = '';
switch (map.iconClass) {
case 'toast-success':
case 'toast-info':
ariaValue = 'polite';
break;
default:
ariaValue = 'assertive';
}
$toastElement.attr('aria-live', ariaValue);
}
function handleEvents() {
if (options.closeOnHover) {
$toastElement.hover(stickAround, delayedHideToast);
}
if (!options.onclick && options.tapToDismiss) {
$toastElement.click(hideToast);
}
if (options.closeButton && $closeElement) {
$closeElement.click(function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else if (event.cancelBubble !== undefined && event.cancelBubble !== true) {
event.cancelBubble = true;
}
if (options.onCloseClick) {
options.onCloseClick(event);
}
hideToast(true);
});
}
if (options.onclick) {
$toastElement.click(function (event) {
options.onclick(event);
hideToast();
});
}
}
function displayToast() {
$toastElement.hide();
$toastElement[options.showMethod](
{duration: options.showDuration, easing: options.showEasing, complete: options.onShown}
);
if (options.timeOut > 0) {
intervalId = setTimeout(hideToast, options.timeOut);
progressBar.maxHideTime = parseFloat(options.timeOut);
progressBar.hideEta = new Date().getTime() + progressBar.maxHideTime;
if (options.progressBar) {
progressBar.intervalId = setInterval(updateProgress, 10);
}
}
}
function setIcon() {
if (map.iconClass) {
$toastElement.addClass(options.toastClass).addClass(iconClass);
}
}
function setSequence() {
if (options.newestOnTop) {
$container.prepend($toastElement);
} else {
$container.append($toastElement);
}
}
function setTitle() {
if (map.title) {
var suffix = map.title;
if (options.escapeHtml) {
suffix = escapeHtml(map.title);
}
$titleElement.append(suffix).addClass(options.titleClass);
$toastElement.append($titleElement);
}
}
function setMessage() {
if (map.message) {
var suffix = map.message;
if (options.escapeHtml) {
suffix = escapeHtml(map.message);
}
$messageElement.append(suffix).addClass(options.messageClass);
$toastElement.append($messageElement);
}
}
function setCloseButton() {
if (options.closeButton) {
$closeElement.addClass(options.closeClass).attr('role', 'button');
$toastElement.prepend($closeElement);
}
}
function setProgressBar() {
if (options.progressBar) {
$progressElement.addClass(options.progressClass);
$toastElement.prepend($progressElement);
}
}
function setRTL() {
if (options.rtl) {
$toastElement.addClass('rtl');
}
}
function shouldExit(options, map) {
if (options.preventDuplicates) {
if (map.message === previousToast) {
return true;
} else {
previousToast = map.message;
}
}
return false;
}
function hideToast(override) {
var method = override && options.closeMethod !== false ? options.closeMethod : options.hideMethod;
var duration = override && options.closeDuration !== false ?
options.closeDuration : options.hideDuration;
var easing = override && options.closeEasing !== false ? options.closeEasing : options.hideEasing;
if ($(':focus', $toastElement).length && !override) {
return;
}
clearTimeout(progressBar.intervalId);
return $toastElement[method]({
duration: duration,
easing: easing,
complete: function () {
removeToast($toastElement);
clearTimeout(intervalId);
if (options.onHidden && response.state !== 'hidden') {
options.onHidden();
}
response.state = 'hidden';
response.endTime = new Date();
publish(response);
}
});
}
function delayedHideToast() {
if (options.timeOut > 0 || options.extendedTimeOut > 0) {
intervalId = setTimeout(hideToast, options.extendedTimeOut);
progressBar.maxHideTime = parseFloat(options.extendedTimeOut);
progressBar.hideEta = new Date().getTime() + progressBar.maxHideTime;
}
}
function stickAround() {
clearTimeout(intervalId);
progressBar.hideEta = 0;
$toastElement.stop(true, true)[options.showMethod](
{duration: options.showDuration, easing: options.showEasing}
);
}
function updateProgress() {
var percentage = ((progressBar.hideEta - (new Date().getTime())) / progressBar.maxHideTime) * 100;
$progressElement.width(percentage + '%');
}
}
function getOptions() {
return $.extend({}, getDefaults(), toastr.options);
}
function removeToast($toastElement) {
if (!$container) { $container = getContainer(); }
if ($toastElement.is(':visible')) {
return;
}
$toastElement.remove();
$toastElement = null;
if ($container.children().length === 0) {
$container.remove();
previousToast = undefined;
}
}
})();
});
}(typeof define === 'function' && define.amd ? define : function (deps, factory) {
if (typeof module !== 'undefined' && module.exports) { //Node
module.exports = factory(require('jquery'));
} else {
window.toastr = factory(window.jQuery);
}
}));
Change your code to be like this:
<a href="#" style="color: rgb(255,0,0,0)" onclick="playclip(); return false;" >xxxxxxxxxxxxx </a>
However, I would reconsider using this type of javascript invokation. Take a look at this "javascript:void(0);" vs "return false" vs "preventDefault()"
I'm using angular 1.4 with requirejs. I need to display the data (loaded from server) in angular grid but I'm having problem in displaying in grid at startup. Data is loaded successfully and not visible in the grid, while when I click on any of it header column, the data is suddenly visible and then it works fine.
Here is the code for loading/displaying the data.
Angular code:
var paginationOptions = {
pageNumber: 1,
pageSize: 25,
sort: null
};
$scope.gridOptions = {
paginationPageSizes: [25, 50, 75],
paginationPageSize: 25,
useExternalPagination: true,
useExternalSorting: false,
columnDefs: [
{name: 'expireDate'},
{name: 'lastUpdateDate'},
{name: 'name'},
{name: 'type'},
],
onRegisterApi: function (gridApi) {
$scope.gridApi = gridApi;
$scope.gridApi.core.on.sortChanged($scope, function (grid, sortColumns) {
if (sortColumns.length === 0) {
paginationOptions.sort = null;
} else {
paginationOptions.sort = sortColumns[0].sort.direction;
}
getPage();
});
gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
paginationOptions.pageNumber = newPage;
paginationOptions.pageSize = pageSize;
getPage();
});
}
};
var getPage = function () {
require(['path/to/jsFile'], function(obj){
obj.getFHVUsersData($scope.gridOptions , paginationOptions);
});
};
getPage();
its working fine and the event getFHVUsersData() is being triggered correctly for requesting data from the server.
Here is code where I'm getting the response from server:
if (ajax.status === 200 && ajax.readyState === 4) {
var resp = JSON.parse(ajax.responseText);
fhvgridOptions.totalItems = resp.data.length;
var firstRow = (paginationOptions.pageNumber - 1) * paginationOptions.pageSize;
fhvgridOptions.data = resp.data.slice(firstRow, firstRow + paginationOptions.pageSize);
}
paginationOptions and fhvgridOptions are the global variables for arguments in the getFHVUsersData($scope.gridOptions , paginationOptions) respectively.
We have a CMS so I don't have access to the header of the HTML page which gets rendered for our extjs implementation. So I had to make a workaround which is like this:
Ext.local = {};
var lang = {
initLang: function (revisionNr) {
var local = localStorage.getItem('localLang')
if (!local) {
AjaxHandlerByClass('ajax/lang/webuser/init', {}, this.loadLangRemote);
} else {
local = JSON.parse(local);
if (local.revisionNr == config.revisionNr && local.lang == config.lang) {
console.log('loading local lang variables');
if (local.date < new Date().getTime() - (24 * 60 * 60 * 1000) * 2) {//2 day caching time before retry
delete window.localStorage.localLangBackup;
}
this.loadLangLocal(local);
} else {
delete window.localStorage.localLang;
AjaxHandlerByClass('ajax/lang/webuser/init', {}, this.loadLangRemote);
}
}
},
loadLangRemote: function (data) {
data.revisionNr = config.revisionNr;
data.lang = config.lang;
data.date = new Date().getTime();
lang.loadLangLocal(data);
localStorage.setItem('localLang', JSON.stringify(data));
},
loadLangLocal: function (data) {
var jsElm = document.createElement("script");
jsElm.type = "application/javascript";
jsElm.src = 'js/freetext-deploy.min.js?rev={/literal}{$revisionNr}{literal}';
document.getElementsByTagName('head')[0].appendChild(jsElm);
Ext.Date.defaultFormat = 'd-m-Y';
if (!debug) {
Ext.Loader.config.disableCaching = true;
}
Ext.application({
name: 'freetextOrder',
appFolder: 'modules/extjs/freetextOrder/app',
controllers: [
'Main'
],
launch: function () {
var freetextOrder = Ext.create('Ext.container.Container', {
renderTo: Ext.get('freetextOrderDiv'),
layout: 'fit',
id: 'catalogAdministrationDiv_ext',
height: 800,
cls: 'x-dig-override',
items: [Ext.create('freetextOrder.view.base.MainView', {})],
layout:'fit'
});
}
});
Ext.local = data;
}
};
lang.initLang();
The problem I'm having is that the minified version gets ignored completely. I see it load on the http request but extjs ignores them.... even though I can see the objects are being created after include (via console log)
Anyone any idea how I can achieve this?
as i see none found the answer so i post my own here wich i came up with.
Since i could for the love of god not load the damn thing i refactored the loader and exported it into a Js. file. wich i reqired and called later on in code.
exported lang.js file:
Ext.define('Lang', {
singleton: true,
ApplicationConf: null,
Launch: function (launchConfig) {
this.ApplicationConf = launchConfig;
var local = localStorage.getItem('localLang');
var me = this;
this.loadLangRemote = function (data) {
debugger;
data.revisionNr = config.revisionNr;
data.lang = config.lang;
data.date = new Date().getTime();
me.loadLangLocal(data);
localStorage.setItem('localLang', JSON.stringify(data));
};
this.loadLangLocal = function (data) {
Ext.local = data;
Ext.lang = function (langId) {
if (Ext.local[langId]) {
return Ext.local[langId];
}
delete window.localStorage.localLang;
localStorage.setItem('localLangBackup', true);
return langId;
}
Ext.application(me.ApplicationConf);
};
if (!local) {
Ext.Ajax.request({
url: 'ajax/lang/webuser/init',
params: {
sid: sid,
},
success: function (data) {
debugger;
me.loadLangRemote(Ext.JSON.decode(data.responseText));
}
})
} else {
local = JSON.parse(local);
if (local.revisionNr == config.revisionNr && local.lang == config.lang) {
console.log('loading local lang variables');
if (local.date < new Date().getTime() - (24 * 60 * 60 * 1000) * 2) {//2 day caching time before retry
delete window.localStorage.localLangBackup;
}
debugger;
me.loadLangLocal(local);
} else {
delete window.localStorage.localLang;
Ext.Ajax.request({
url: 'ajax/lang/webuser/init',
params: {
sid: sid,
},
success: function (data) {
me.loadLangRemote(Ext.JSON.decode(data.responseText));
}
})
}
}
},
})
And IMPORTANT was to add the
Ext.onReady(function () {
Lang.Launch({
name: 'catalogAdministration',
appFold....
To the call of the Launch function in code, bacause it would have been not defined at run time. i added the file to the minified file first and call the Lang.Launch instead Ext.Application.
Hope somone has use of my solution :)
I have tried to reload the data populated by an ajax call but I cant get it to work, it shows the old data even after using the reload method. The thing is that if I change some variables to populate a different data and try to call the following code without refreshing the page it does not reload the updated data =/ Here is my code:
function populateDataGrid() {
$.ajaxSetup({async: false});
var gridinfo="";
$.post("lib/function.php",{activity: activity, shift: shift, date: date},
function (output){
gridinfo = JSON.parse(output);
});
$.ajaxSetup({async: true});
// INITIALIZING THE DATAGRID
var dataSource = new StaticDataSource({
columns: [
{
property: 'id',
label: '#',
sortable: true
},
{
property: 'date',
label: 'date',
sortable: true
},
....
],
formatter: function (items) {
var c=1;
$.each(items, function (index, item) {
item.select = '<input type="button" id="select'+c+'" class="select btn" value="select" onclick="">';
c=c+1;
});
},
data: gridinfo,
delay:300
});
$('#grid').datagrid({
dataSource: dataSource
});
$('#grid').datagrid('reload');
$('#modal-fast-appointment-results').modal({show:true});
}
I found a solution... I had to create a new DataSource (lets call it "AjaxDataSource") and add the ajax request functionality within the data constructor:
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['underscore'], factory);
} else {
root.AjaxDataSource = factory();
}
}(this, function () {
var AjaxDataSource = function (options) {
this._formatter = options.formatter;
this._columns = options.columns;
this._delay = options.delay || 0;
this._data = options.data;
};
AjaxDataSource.prototype = {
columns: function () {
return this._columns;
},
data: function (options, callback) {
var self = this;
setTimeout(function () {
var data;
$.ajax({
url: 'getdata.php',
type: 'POST',
data: 'param1:param1,param2,param2,...,paramN:paramN', // this is optional in case you have to send some params to getdata.php
dataType: 'json',
async: false,
success: function(result) {
data = result;
},
error: function(data){
//in case we want to debug and catch any possible error
// console.log(data);
}
});
// SEARCHING
if (options.search) {
data = _.filter(data, function (item) {
var match = false;
_.each(item, function (prop) {
if (_.isString(prop) || _.isFinite(prop)) {
if (prop.toString().toLowerCase().indexOf(options.search.toLowerCase()) !== -1) match = true;
}
});
return match;
});
}
var count = data.length;
// SORTING
if (options.sortProperty) {
data = _.sortBy(data, options.sortProperty);
if (options.sortDirection === 'desc') data.reverse();
}
// PAGING
var startIndex = options.pageIndex * options.pageSize;
var endIndex = startIndex + options.pageSize;
var end = (endIndex > count) ? count : endIndex;
var pages = Math.ceil(count / options.pageSize);
var page = options.pageIndex + 1;
var start = startIndex + 1;
data = data.slice(startIndex, endIndex);
if (self._formatter) self._formatter(data);
callback({ data: data, start: start, end: end, count: count, pages: pages, page: page });
}, this._delay)
}
};
return AjaxDataSource;
}));
After defining the new DataSource, we just need to create it and call the datagrid as usual:
function populateDataGrid(){
// INITIALIZING THE DATAGRID
var dataSource = new AjaxDataSource({
columns: [
{
property: 'id',
label: '#',
sortable: true
},
{
property: 'date',
label: 'date',
sortable: true
},
....
],
formatter: function (items) { // in case we want to add customized items, for example a button
var c=1;
$.each(items, function (index, item) {
item.select = '<input type="button" id="select'+c+'" class="select btn" value="select" onclick="">';
c=c+1;
});
},
delay:300
});
$('#grid').datagrid({
dataSource: dataSource
});
$('#grid').datagrid('reload');
$('#modal-results').modal({show:true});
}
So now we have our datagrid with data populated via ajax request with the ability to reload the data without refreshing the page.
Hope it helps someone!