import ngModule from '../../module'; import Component from '../../lib/component'; import './style.scss'; export default class SmartTable extends Component { constructor($element, $, $transclude) { super($element, $); this.$transclude = $transclude; this.sortCriteria = []; this.autoSave = false; } get model() { return this._model; } set model(value) { this._model = value; if (value) { this.$.model = value; this.transclude(); } } get checkedRows() { const model = this.model; if (model && model.data) return model.data.filter(row => row.$checked); return null; } registerColumns() { const header = this.element.querySelector('thead > tr'); if (!header) return; const columns = header.querySelectorAll('th'); // Click handler for (let column of columns) { const field = column.getAttribute('field'); if (field) column.addEventListener('click', () => this.orderHandler(column)); } } // Creo que se puede hacer directamente desde ng-transclude transclude() { const slotTable = this.element.querySelector('#table'); this.$transclude(($clone, $scope) => { const table = $clone[0]; $scope.hasChanges = this.hasChanges; slotTable.appendChild(table); this.registerColumns(); }, null, 'table'); } orderHandler(element) { const field = element.getAttribute('field'); const existingCriteria = this.sortCriteria.find(criteria => { return criteria.field == field; }); if (!existingCriteria) { this.sortCriteria.push({field: field, sortType: 'ASC'}); element.classList.remove('desc'); element.classList.add('asc'); } if (existingCriteria && existingCriteria.sortType == 'DESC') { this.sortCriteria.splice(this.sortCriteria.findIndex(criteria => { return criteria.field == field; }), 1); element.classList.remove('desc'); element.classList.remove('asc'); } if (existingCriteria && existingCriteria.sortType == 'ASC') { existingCriteria.sortType = 'DESC'; element.classList.remove('asc'); element.classList.add('desc'); } this.applySort(); } applySort() { let order = this.sortCriteria.map(criteria => `${criteria.field} ${criteria.sortType}`); order = order.join(', '); if (order) this.model.order = order; this.model.refresh(); } createRow() { this.model.insert({ nickname: 'New row' }); } deleteAll() { const rowsChecked = this.checkedRows(); for (let row of rowsChecked) this.model.removeRow(row); if (this.autoSave) this.saveAll(); } saveAll() { const model = this.model; if (!model.isChanged) return this.vnApp.showError(this.$t('No changes to save')); this.model.save() .then(() => this.vnApp.showSuccess(this.$t('Data saved!'))); } hasChanges() { return true; } } SmartTable.$inject = ['$element', '$scope', '$transclude']; ngModule.vnComponent('smartTable', { template: require('./index.html'), controller: SmartTable, transclude: { table: '?slotTable', actions: '?slotActions' }, bindings: { model: '