UNPKG

@omostan/angularjs-xeditable

Version:

A customized version of xeditable - a bundle of AngularJS directives that allows you to create editable elements in your projects. Such technique is also known as click-to-edit or edit-in-place.

1,423 lines (1,241 loc) 92.3 kB
/*! angular-xeditable - 0.8.1 Edit-in-place for angular.js Build date: 2017-11-14 */ /** * Angular-xeditable module * */ angular.module('xeditable', []) /** * Default options. * * @namespace editable-options */ //todo: maybe better have editableDefaults, not options... .value('editableOptions', { /** * Theme. Possible values `bs3`, `bs2`, `default`. * Default is `default` * * @var {string} theme * @memberOf editable-options */ theme: 'default', /** * icon_set. Possible values `font-awesome`, `default`. * Default is `default` * * @var {string} icon set * @memberOf editable-options */ icon_set: 'default', /** * Whether to show buttons for single editable element. * Possible values `right`, `no`. * Default is `right` * * @var {string} buttons * @memberOf editable-options */ buttons: 'right', /** * Default value for `blur` attribute of single editable element. * Can be `cancel|submit|ignore`. * Default is `cancel` * * @var {string} blurElem * @memberOf editable-options */ blurElem: 'cancel', /** * Default value for `blur` attribute of editable form. * Can be `cancel|submit|ignore`. * Default is `ignore`. * * @var {string} blurForm * @memberOf editable-options */ blurForm: 'ignore', /** * How input elements get activated. Possible values: `focus|select|none`. * Default is `focus` * * @var {string} activate * @memberOf editable-options */ activate: 'focus', /** * Whether to disable x-editable. Can be overloaded on each element. * Default is `false` * * @var {boolean} isDisabled * @memberOf editable-options */ isDisabled: false, /** * Event, on which the edit mode gets activated. * Can be any event. * Default is `click` * * @var {string} activationEvent * @memberOf editable-options */ activationEvent: 'click', /** * The default title of the submit button. * Default is `Submit` * * @var {string} submitButtonTitle * @memberOf editable-options */ submitButtonTitle: 'Submit', /** * The default aria label of the submit button. * Default is `Submit` * * @var {string} submitButtonAriaLabel * @memberOf editable-options */ submitButtonAriaLabel: 'Submit', /** * The default title of the cancel button. * Default is `Cancel` * * @var {string} cancelButtonTitle * @memberOf editable-options */ cancelButtonTitle: 'Cancel', /** * The default aria label of the cancel button. * Default is `Cancel` * * @var {string} cancelButtonAriaLabel * @memberOf editable-options */ cancelButtonAriaLabel: 'Cancel', /** * The default title of the clear button. * Default is `Clear` * * @var {string} clearButtonTitle * @memberOf editable-options */ clearButtonTitle: 'Clear', /** * The default aria label of the clear button. * Default is `Clear` * * @var {string} clearButtonAriaLabel * @memberOf editable-options */ clearButtonAriaLabel: 'Clear', /** * Whether to display the clear button. * Default is `false` * * @var {boolean} displayClearButton * @memberOf editable-options */ displayClearButton: false, /** * Whether not to display the submit button. * Default is `false` * * @var {boolean} displaySubmitButton * @memberOf editable-options */ displaySubmitButton: false }); /* Angular-ui bootstrap datepicker http://angular-ui.github.io/bootstrap/#/datepicker */ angular.module('xeditable').directive('editableBsdate', ['editableDirectiveFactory', '$injector', '$parse', function(editableDirectiveFactory, $injector, $parse) { // Constants from Angular-ui bootstrap datepicker uibDatepickerConfig = $injector.get('uibDatepickerConfig'); uibDatepickerPopupConfig = $injector.get('uibDatepickerPopupConfig'); var popupAttrNames = [ ['eIsOpen', 'is-open'], ['eDateDisabled', 'date-disabled'], ['eDatepickerPopup', 'uib-datepicker-popup'], ['eShowButtonBar', 'show-button-bar'], ['eCurrentText', 'current-text'], ['eClearText', 'clear-text'], ['eCloseText', 'close-text'], ['eCloseOnDateSelection', 'close-on-date-selection'], ['eDatepickerAppendToBody', 'datepicker-append-to-body'], ['eOnOpenFocus', 'on-open-focus'], ['eName', 'name'], ['eDateDisabled', 'date-disabled'], ['eAltInputFormats', 'alt-input-formats'] ]; var dateOptionsNames = [ ['eFormatDay', 'formatDay'], ['eFormatMonth', 'formatMonth'], ['eFormatYear', 'formatYear'], ['eFormatDayHeader', 'formatDayHeader'], ['eFormatDayTitle', 'formatDayTitle'], ['eFormatMonthTitle', 'formatMonthTitle'], ['eMaxMode', 'maxMode'], ['eMinMode', 'minMode'], ['eDatepickerMode', 'datepickerMode'] ]; return editableDirectiveFactory({ directiveName: 'editableBsdate', inputTpl: '<div></div>', render: function() { /** This basically renders a datepicker as in the example shown in ** http://angular-ui.github.io/bootstrap/#/datepicker ** The attributes are all the same as in the bootstrap-ui datepicker with e- as prefix **/ this.parent.render.call(this); var attrs = this.attrs; var scope = this.scope; var inputDatePicker = angular.element('<input type="text" class="form-control" ng-model="$parent.$data"/>'); inputDatePicker.attr('uib-datepicker-popup', attrs.eDatepickerPopupXEditable || uibDatepickerPopupConfig.datepickerPopup ); inputDatePicker.attr('year-range', attrs.eYearRange || 20); inputDatePicker.attr('ng-readonly', attrs.eReadonly || false); for (var i = popupAttrNames.length - 1; i >= 0; i--) { var popupAttr = attrs[popupAttrNames[i][0]]; if (typeof popupAttr !== 'undefined') { inputDatePicker.attr(popupAttrNames[i][1], popupAttr); } } if (attrs.eNgChange) { inputDatePicker.attr('ng-change', attrs.eNgChange); this.inputEl.removeAttr('ng-change'); } if (attrs.eStyle) { inputDatePicker.attr('style', attrs.eStyle); this.inputEl.removeAttr('style'); } var dateOptions = { maxDate: scope.$eval(attrs.eMaxDate) || uibDatepickerConfig.maxDate, minDate: scope.$eval(attrs.eMinDate) || uibDatepickerConfig.minDate, showWeeks: attrs.eShowWeeks ? attrs.eShowWeeks.toLowerCase() === 'true' : uibDatepickerConfig.showWeeks, startingDay: attrs.eStartingDay || 0, initDate: scope.$eval(attrs.eInitDate) || new Date() }; if (attrs.eDatepickerOptions) { var eDatepickerOptions = $parse(attrs.eDatepickerOptions)(scope); angular.extend(dateOptions, eDatepickerOptions); } for (var z = dateOptionsNames.length - 1; z >= 0; z--) { var doAttr = attrs[dateOptionsNames[z][0]]; if (typeof doAttr !== 'undefined') { dateOptions[dateOptionsNames[z][1]] = doAttr; } } scope.dateOptions = dateOptions; var showCalendarButton = angular.isDefined(attrs.eShowCalendarButton) ? attrs.eShowCalendarButton : "true"; //See if calendar button should be displayed if (showCalendarButton === "true") { var buttonDatePicker = angular.element('<button type="button" class="btn btn-default"><i class="glyphicon glyphicon-calendar"></i></button>'); var buttonWrapper = angular.element('<span class="input-group-btn"></span>'); buttonDatePicker.attr('ng-click', attrs.eNgClick); buttonWrapper.append(buttonDatePicker); this.inputEl.append(buttonWrapper); } else { //If no calendar button, display calendar popup on click of input field inputDatePicker.attr('ng-click', attrs.eNgClick); } inputDatePicker.attr('datepicker-options', "dateOptions"); this.inputEl.prepend(inputDatePicker); this.inputEl.removeAttr('class'); this.inputEl.removeAttr('ng-click'); this.inputEl.removeAttr('is-open'); this.inputEl.removeAttr('init-date'); this.inputEl.removeAttr('datepicker-popup'); this.inputEl.removeAttr('required'); this.inputEl.removeAttr('ng-model'); this.inputEl.removeAttr('date-picker-append-to-body'); this.inputEl.removeAttr('name'); this.inputEl.attr('class','input-group'); }, autosubmit: function() { var self = this; self.inputEl.bind('change', function() { setTimeout(function() { self.scope.$apply(function() { self.scope.$form.$submit(); }); }, 500); }); self.inputEl.bind('keydown', function(e) { //submit on tab if (e.keyCode === 9 && self.editorEl.attr('blur') === 'submit') { self.scope.$apply(function() { self.scope.$form.$submit(); }); } }); } }); }]); /* Angular-ui bootstrap editable timepicker http://angular-ui.github.io/bootstrap/#/timepicker */ angular.module('xeditable').directive('editableBstime', ['editableDirectiveFactory', function(editableDirectiveFactory) { return editableDirectiveFactory({ directiveName: 'editableBstime', inputTpl: '<div uib-timepicker></div>', render: function() { this.parent.render.call(this); // timepicker can't update model when ng-model set directly to it // see: https://github.com/angular-ui/bootstrap/issues/1141 // so we wrap it into DIV var div = angular.element('<div class="well well-small" style="display:inline-block;"></div>'); // move ng-model to wrapping div div.attr('ng-model', this.inputEl.attr('ng-model')); this.inputEl.removeAttr('ng-model'); // move ng-change to wrapping div if(this.attrs.eNgChange) { div.attr('ng-change', this.inputEl.attr('ng-change')); this.inputEl.removeAttr('ng-change'); } // wrap this.inputEl.wrap(div); } }); }]); //checkbox angular.module('xeditable').directive('editableCheckbox', ['editableDirectiveFactory', function(editableDirectiveFactory) { return editableDirectiveFactory({ directiveName: 'editableCheckbox', inputTpl: '<input type="checkbox">', render: function() { this.parent.render.call(this); this.inputEl.wrap('<label></label>'); if (this.attrs.eTitle) { this.inputEl.parent().append('<span>' + this.attrs.eTitle + '</span>'); } }, autosubmit: function() { var self = this; self.inputEl.bind('change', function() { setTimeout(function() { self.scope.$apply(function() { self.scope.$form.$submit(); }); }, 500); }); } }); }]); // checklist angular.module('xeditable').directive('editableChecklist', [ 'editableDirectiveFactory', 'editableNgOptionsParser', function(editableDirectiveFactory, editableNgOptionsParser) { return editableDirectiveFactory({ directiveName: 'editableChecklist', inputTpl: '<span></span>', useCopy: true, render: function() { this.parent.render.call(this); var parsed = editableNgOptionsParser(this.attrs.eNgOptions); var ngChangeHtml = ''; var ngChecklistComparatorHtml = ''; if (this.attrs.eNgChange) { ngChangeHtml = ' ng-change="' + this.attrs.eNgChange + '"'; } if (this.attrs.eChecklistComparator) { ngChecklistComparatorHtml = ' checklist-comparator="' + this.attrs.eChecklistComparator + '"'; } var html = '<label ng-repeat="'+parsed.ngRepeat+'">'+ '<input type="checkbox" checklist-model="$parent.$parent.$data" checklist-value="'+parsed.locals.valueFn+'"' + ngChangeHtml + ngChecklistComparatorHtml + '>'+ '<span ng-bind="'+parsed.locals.displayFn+'"></span></label>'; this.inputEl.removeAttr('ng-model'); this.inputEl.removeAttr('ng-options'); this.inputEl.removeAttr('ng-change'); this.inputEl.removeAttr('checklist-comparator'); this.inputEl.html(html); } }); }]); angular.module('xeditable').directive('editableCombodate', ['editableDirectiveFactory', 'editableCombodate', function(editableDirectiveFactory, editableCombodate) { return editableDirectiveFactory({ directiveName: 'editableCombodate', inputTpl: '<input type="text">', render: function() { this.parent.render.call(this); var options = { value: new Date(this.scope.$data) }; var self = this; angular.forEach(["format", "template", "minYear", "maxYear", "yearDescending", "minuteStep", "secondStep", "firstItem", "errorClass", "customClass", "roundTime", "smartDays"], function(name) { var attrName = "e" + name.charAt(0).toUpperCase() + name.slice(1); if (attrName in self.attrs) { if (name == "minYear" || name == "maxYear" || name == "minuteStep" || name == "secondStep") { options[name] = parseInt(self.attrs[attrName], 10); } else { options[name] = self.attrs[attrName]; } } }); var combodate = editableCombodate.getInstance(this.inputEl, options); combodate.$widget.find('select').bind('change', function(e) { //.replace is so this works in Safari self.scope.$data = combodate.getValue() ? (new Date(combodate.getValue().replace(/-/g, "/"))).toISOString() : null; }).change(); } }); } ]); /* Input types: text|password|email|tel|number|url|search|color|date|datetime|datetime-local|time|month|week|file */ (function() { var camelCase = function(dashDelimitedString) { return dashDelimitedString.toLowerCase().replace(/-(.)/g, function(match, word) { return word.toUpperCase(); }); }; var types = 'text|password|email|tel|number|url|search|color|date|datetime|datetime-local|time|month|week|file'.split('|'); //todo: datalist // generate directives angular.forEach(types, function(type) { var directiveName = camelCase('editable' + '-' + type); angular.module('xeditable').directive(directiveName, ['editableDirectiveFactory', function(editableDirectiveFactory) { return editableDirectiveFactory({ directiveName: directiveName, inputTpl: '<input type="'+type+'">', render: function() { this.parent.render.call(this); //Add bootstrap simple input groups if (this.attrs.eInputgroupleft || this.attrs.eInputgroupright) { this.inputEl.wrap('<div class="input-group"></div>'); if (this.attrs.eInputgroupleft) { var inputGroupLeft = angular.element('<span class="input-group-addon">' + this.attrs.eInputgroupleft + '</span>'); this.inputEl.parent().prepend(inputGroupLeft); } if (this.attrs.eInputgroupright) { var inputGroupRight = angular.element('<span class="input-group-addon">' + this.attrs.eInputgroupright + '</span>'); this.inputEl.parent().append(inputGroupRight); } } // Add label to the input if (this.attrs.eLabel) { var label = angular.element('<label>' + this.attrs.eLabel + '</label>'); if (this.attrs.eInputgroupleft || this.attrs.eInputgroupright) { this.inputEl.parent().parent().prepend(label); } else { this.inputEl.parent().prepend(label); } } // Add classes to the form if (this.attrs.eFormclass) { this.editorEl.addClass(this.attrs.eFormclass); this.inputEl.removeAttr('formclass'); } }, autosubmit: function() { var self = this; self.inputEl.bind('keydown', function(e) { //submit on tab if (e.keyCode === 9 && self.editorEl.attr('blur') === 'submit') { self.scope.$apply(function() { self.scope.$form.$submit(); }); } }); } }); }]); }); //`range` is bit specific angular.module('xeditable').directive('editableRange', ['editableDirectiveFactory', '$interpolate', function(editableDirectiveFactory, $interpolate) { return editableDirectiveFactory({ directiveName: 'editableRange', inputTpl: '<input type="range" id="range" name="range">', render: function() { this.parent.render.call(this); this.inputEl.after('<output>' + $interpolate.startSymbol() + '$data' + $interpolate.endSymbol() + '</output>'); } }); }]); }()); /* Tags input directive for AngularJS https://github.com/mbenford/ngTagsInput */ angular.module('xeditable').directive('editableTagsInput', ['editableDirectiveFactory', 'editableUtils', function(editableDirectiveFactory, editableUtils) { var dir = editableDirectiveFactory({ directiveName: 'editableTagsInput', inputTpl: '<tags-input></tags-input>', useCopy: true, render: function () { this.parent.render.call(this); this.inputEl.append(editableUtils.rename('auto-complete', this.attrs.$autoCompleteElement)); this.inputEl.removeAttr('ng-model'); this.inputEl.attr('ng-model', '$parent.$data'); } }); var linkOrg = dir.link; dir.link = function (scope, el, attrs, ctrl) { var autoCompleteEl = el.find('editable-tags-input-auto-complete'); attrs.$autoCompleteElement = autoCompleteEl.clone(); autoCompleteEl.remove(); return linkOrg(scope, el, attrs, ctrl); }; return dir; }]); // radiolist angular.module('xeditable').directive('editableRadiolist', [ 'editableDirectiveFactory', 'editableNgOptionsParser', '$interpolate', function(editableDirectiveFactory, editableNgOptionsParser, $interpolate) { return editableDirectiveFactory({ directiveName: 'editableRadiolist', inputTpl: '<span></span>', render: function() { this.parent.render.call(this); var parsed = editableNgOptionsParser(this.attrs.eNgOptions), ngChangeHtml = '', ngNameHtml = ''; if (this.attrs.eNgChange) { ngChangeHtml = ' ng-change="' + this.attrs.eNgChange + '"'; } if (this.attrs.eName) { ngNameHtml = ' name="' + this.attrs.eName + '"'; } var html = '<label data-ng-repeat="'+parsed.ngRepeat+'">'+ '<input type="radio" data-ng-disabled="::' + this.attrs.eNgDisabled + '" data-ng-model="$parent.$parent.$data" data-ng-value="' + $interpolate.startSymbol() + '::' + parsed.locals.valueFn + $interpolate.endSymbol() +'"' + ngChangeHtml + ngNameHtml + '>'+ '<span data-ng-bind="::'+parsed.locals.displayFn+'"></span></label>'; this.inputEl.removeAttr('ng-model'); this.inputEl.removeAttr('ng-options'); this.inputEl.removeAttr('ng-change'); this.inputEl.html(html); }, autosubmit: function() { var self = this; self.inputEl.bind('change', function() { setTimeout(function() { self.scope.$apply(function() { self.scope.$form.$submit(); }); }, 500); }); } }); }]); //select angular.module('xeditable').directive('editableSelect', ['editableDirectiveFactory', function(editableDirectiveFactory) { return editableDirectiveFactory({ directiveName: 'editableSelect', inputTpl: '<select></select>', render: function() { this.parent.render.call(this); if (this.attrs.ePlaceholder) { var placeholder = angular.element('<option value="">' + this.attrs.ePlaceholder + '</option>'); this.inputEl.append(placeholder); } }, autosubmit: function() { var self = this; if (!self.attrs.hasOwnProperty("eMultiple")) { self.inputEl.bind('change', function () { self.scope.$apply(function () { self.scope.$form.$submit(); }); }); } } }); }]); //textarea angular.module('xeditable').directive('editableTextarea', ['editableDirectiveFactory', function(editableDirectiveFactory) { return editableDirectiveFactory({ directiveName: 'editableTextarea', inputTpl: '<textarea></textarea>', render: function() { this.parent.render.call(this); // Add classes to the form if (this.attrs.eFormclass) { this.editorEl.addClass(this.attrs.eFormclass); this.inputEl.removeAttr('formclass'); } }, addListeners: function() { var self = this; self.parent.addListeners.call(self); // submit textarea by ctrl+enter even with buttons if (self.single && self.buttons !== 'no') { self.autosubmit(); } }, autosubmit: function() { var self = this; self.inputEl.bind('keydown', function(e) { if (self.attrs.submitOnEnter) { if (e.keyCode === 13 && !e.shiftKey) { self.scope.$apply(function() { self.scope.$form.$submit(); }); } } else if ((e.ctrlKey || e.metaKey) && (e.keyCode === 13) || (e.keyCode === 9 && self.editorEl.attr('blur') === 'submit')) { self.scope.$apply(function() { self.scope.$form.$submit(); }); } }); } }); }]); /* jQuery UI Datepicker for AngularJS https://github.com/angular-ui/ui-date */ angular.module('xeditable').directive('editableUidate', ['editableDirectiveFactory', function(editableDirectiveFactory) { return editableDirectiveFactory({ directiveName: 'editableUidate', inputTpl: '<input class="form-control" />', render: function() { this.parent.render.call(this); this.inputEl.attr('ui-date', this.attrs.eUiDate); this.inputEl.attr('placeholder', this.attrs.ePlaceholder); } }); }]); /* AngularJS-native version of Select2 and Selectize https://github.com/angular-ui/ui-select */ angular.module('xeditable').directive('editableUiSelect',['editableDirectiveFactory', 'editableUtils', function(editableDirectiveFactory, editableUtils) { var dir = editableDirectiveFactory({ directiveName: 'editableUiSelect', inputTpl: '<ui-select></ui-select>', render: function () { this.parent.render.call(this); this.inputEl.append(editableUtils.rename('ui-select-match', this.attrs.$matchElement)); this.inputEl.append(editableUtils.rename('ui-select-choices', this.attrs.$choicesElement)); this.inputEl.removeAttr('ng-model'); this.inputEl.attr('ng-model', '$parent.$parent.$data'); }, autosubmit: function() { var self = this; self.inputEl.bind('change', function() { setTimeout(function() { self.scope.$apply(function() { self.scope.$form.$submit(); }); }, 500); }); self.inputEl.bind('keydown', function(e) { //submit on tab if (e.keyCode === 9 && self.editorEl.attr('blur') === 'submit') { self.scope.$apply(function() { self.scope.$form.$submit(); }); } }); } }); var linkOrg = dir.link; dir.link = function (scope, el, attrs, ctrl) { var matchEl = el.find('editable-ui-select-match'); var choicesEl = el.find('editable-ui-select-choices'); attrs.$matchElement = matchEl.clone(); attrs.$choicesElement = choicesEl.clone(); matchEl.remove(); choicesEl.remove(); return linkOrg(scope, el, attrs, ctrl); }; return dir; }]); /** * EditableController class. * Attached to element with `editable-xxx` directive. * * @namespace editable-element */ /* TODO: this file should be refactored to work more clear without closures! */ angular.module('xeditable').factory('editableController', ['$q', 'editableUtils', function($q, editableUtils) { //EditableController function EditableController.$inject = ['$scope', '$attrs', '$element', '$parse', 'editableThemes', 'editableIcons', 'editableOptions', '$rootScope', '$compile', '$q', '$sce', '$templateCache']; function EditableController($scope, $attrs, $element, $parse, editableThemes, editableIcons, editableOptions, $rootScope, $compile, $q, $sce, $templateCache) { var valueGetter; //if control is disabled - it does not participate in waiting process var inWaiting; var self = this; self.scope = $scope; self.elem = $element; self.attrs = $attrs; self.inputEl = null; self.editorEl = null; self.single = true; self.error = ''; self.theme = editableThemes[$attrs.editableTheme] || editableThemes[editableOptions.theme] || editableThemes['default']; self.parent = {}; //will be undefined if icon_set is default and theme is default var theme_name = $attrs.editableTheme || editableOptions.theme || 'default'; // The theme_name will not be correct if the theme set in options is unavailable // However, in that case an undefined icon_set is not that bad... var icon_set_option = $attrs.editableIconSet || editableOptions.icon_set; self.icon_set = icon_set_option === 'default' ? editableIcons.default[theme_name] : editableIcons.external[icon_set_option]; //to be overwritten by directive self.inputTpl = ''; self.directiveName = ''; // with majority of controls copy is not needed, but.. // copy MUST NOT be used for `select-multiple` with objects as items // copy MUST be used for `checklist` self.useCopy = false; //runtime (defaults) self.single = null; /** * Attributes defined with `e-*` prefix automatically transferred from original element to * control. * For example, if you set `<span editable-text="user.name" e-style="width: 100px"`> * then input will appear as `<input style="width: 100px">`. * See [demo](#text-customize). * * @var {any|attribute} e-* * @memberOf editable-element */ /** * Whether to show ok/cancel buttons. Values: `right|no`. * If set to `no` control automatically submitted when value changed. * If control is part of form buttons will never be shown. * * @var {string|attribute} buttons * @memberOf editable-element */ self.buttons = 'right'; /** * Whether to show the editable element in a ui-bootstrap popover. Values: `true|false`. * * @var {boolean|attribute} popover * @memberOf editable-element */ self.popover = false; /** * Action when control losses focus. Values: `cancel|submit|ignore`. * Has sense only for single editable element. * Otherwise, if control is part of form - you should set `blur` of form, not of individual element. * * @var {string|attribute} blur * @memberOf editable-element */ // no real `blur` property as it is transferred to editable form //init self.init = function(single) { self.single = single; self.name = $attrs.eName || $attrs[self.directiveName]; /* if(!$attrs[directiveName] && !$attrs.eNgModel && ($attrs.eValue === undefined)) { throw 'You should provide value for `'+directiveName+'` or `e-value` in editable element!'; } */ if($attrs[self.directiveName]) { valueGetter = $parse($attrs[self.directiveName]); } else { throw 'You should provide value for `'+self.directiveName+'` in editable element!'; } // settings for single and non-single if (!self.single) { // hide buttons for non-single self.buttons = 'no'; } else { self.buttons = self.attrs.buttons || editableOptions.buttons; } //if name defined --> watch changes and update $data in form if($attrs.eName) { self.scope.$watch('$data', function(newVal){ self.scope.$form.$data[$attrs.eName] = newVal; }); } /** * Called when control is shown. * See [demo](#select-remote). * * @var {method|attribute} onshow * @memberOf editable-element */ if($attrs.onshow) { self.onshow = function() { return self.catchError($parse($attrs.onshow)($scope)); }; } /** * Called when control is hidden after both save or cancel. * * @var {method|attribute} onhide * @memberOf editable-element */ if ($attrs.onhide) { self.onhide = function() { return $parse($attrs.onhide)($scope); }; } /** * Called when control is cancelled. * * @var {method|attribute} oncancel * @memberOf editable-element */ if ($attrs.oncancel) { self.oncancel = function() { return $parse($attrs.oncancel)($scope); }; } /** * Called during submit before value is saved to model. * See [demo](#onbeforesave). * * @var {method|attribute} onbeforesave * @memberOf editable-element */ if ($attrs.onbeforesave) { self.onbeforesave = function() { return self.catchError($parse($attrs.onbeforesave)($scope)); }; } /** * Called during submit after value is saved to model. * See [demo](#onaftersave). * * @var {method|attribute} onaftersave * @memberOf editable-element */ if ($attrs.onaftersave) { self.onaftersave = function() { return self.catchError($parse($attrs.onaftersave)($scope)); }; } if ($attrs.popover) { self.popover = self.attrs.popover; } // watch change of model to update editable element // now only add/remove `editable-empty` class. // Initially this method called with newVal = undefined, oldVal = undefined // so no need initially call handleEmpty() explicitly $scope.$parent.$watch($attrs[self.directiveName], function(newVal, oldVal) { self.setLocalValue(); self.handleEmpty(); }); }; self.render = function() { var theme = self.theme; //build input self.inputEl = angular.element(self.inputTpl); //build controls self.controlsEl = angular.element(theme.controlsTpl); self.controlsEl.append(self.inputEl); //build buttons if(self.buttons !== 'no') { self.buttonsEl = angular.element(theme.buttonsTpl); self.submitEl = angular.element(theme.submitTpl); self.resetEl = angular.element(theme.resetTpl); self.cancelEl = angular.element(theme.cancelTpl); self.submitEl.attr('title', editableOptions.submitButtonTitle); self.submitEl.attr('aria-label', editableOptions.submitButtonAriaLabel); self.cancelEl.attr('title', editableOptions.cancelButtonTitle); self.cancelEl.attr('aria-label', editableOptions.cancelButtonAriaLabel); self.resetEl.attr('title', editableOptions.clearButtonTitle); self.resetEl.attr('aria-label', editableOptions.clearButtonAriaLabel); if (self.icon_set) { self.submitEl.find('span').addClass(self.icon_set.ok); self.cancelEl.find('span').addClass(self.icon_set.cancel); self.resetEl.find('span').addClass(self.icon_set.clear); } /** * Added by Stanley Omoregie (stan@omotech.com) on October 17, 2019 and edited on October 24, 2019 * If the attribute (display-submit-button) is configured directly on the element, this takes preceedings. * Otherwise, the attribute (editableOptions.displaySubmitButton) value set on the application run level will be evaluated. */ if (self.attrs.displaySubmitButton !== undefined) { self.attrs.displaySubmitButton === 'true' ? self.buttonsEl.append(self.submitEl).append(self.cancelEl) : self.buttonsEl.append(self.cancelEl); } else { editableOptions.displaySubmitButton ? self.buttonsEl.append(self.submitEl).append(self.cancelEl) : self.buttonsEl.append(self.cancelEl); } if (editableOptions.displayClearButton) { self.buttonsEl.append(self.resetEl); } self.controlsEl.append(self.buttonsEl); self.inputEl.addClass('editable-has-buttons'); } //build error self.errorEl = angular.element(theme.errorTpl); self.controlsEl.append(self.errorEl); //build editor self.editorEl = angular.element(self.single ? theme.formTpl : theme.noformTpl); self.editorEl.append(self.controlsEl); // transfer `e-*|data-e-*|x-e-*` attributes for (var k in $attrs.$attr) { if(k.length <= 1) { continue; } var transferAttr = false; var nextLetter = k.substring(1, 2); // if starts with `e` + uppercase letter if (k.substring(0, 1) === 'e' && nextLetter === nextLetter.toUpperCase()) { transferAttr = k.substring(1); // cut `e` } else { continue; } // exclude `form` and `ng-submit`, if (transferAttr === 'Form' || transferAttr === 'NgSubmit') { continue; } var firstLetter = transferAttr.substring(0, 1); var secondLetter = transferAttr.substring(1, 2); // convert back to lowercase style if (secondLetter === secondLetter.toUpperCase() && firstLetter === firstLetter.toUpperCase()) { transferAttr = firstLetter.toLowerCase() + '-' + editableUtils.camelToDash(transferAttr.substring(1)); } else { transferAttr = firstLetter.toLowerCase() + editableUtils.camelToDash(transferAttr.substring(1)); } // workaround for attributes without value (e.g. `multiple = "multiple"`) // except for 'e-value' var attrValue = (transferAttr !== 'value' && $attrs[k] === '') ? transferAttr : $attrs[k]; // set attributes to input self.inputEl.attr(transferAttr, attrValue); } self.inputEl.addClass('editable-input'); self.inputEl.attr('ng-model', '$parent.$data'); // add directiveName class to editor, e.g. `editable-text` self.editorEl.addClass(editableUtils.camelToDash(self.directiveName)); if (self.single) { self.editorEl.attr('editable-form', '$form'); // transfer `blur` to form self.editorEl.attr('blur', self.attrs.blur || editableOptions.blurElem); } if (self.popover) { var wrapper = angular.element('<div></div>'); wrapper.append(self.editorEl); self.editorEl = wrapper; $templateCache.put('popover.html', self.editorEl[0].outerHTML); } //apply `postrender` method of theme if (angular.isFunction(theme.postrender)) { theme.postrender.call(self); } }; // with majority of controls copy is not needed, but.. // copy MUST NOT be used for `select-multiple` with objects as items // copy MUST be used for `checklist` self.setLocalValue = function() { self.scope.$data = self.useCopy ? angular.copy(valueGetter($scope.$parent)) : valueGetter($scope.$parent); }; // reference of the scope to use for $compile var newScope = null; //show self.show = function() { // set value of scope.$data self.setLocalValue(); /* Originally render() was inside init() method, but some directives polluting editorEl, so it is broken on second opening. Cloning is not a solution as jqLite can not clone with event handler's. */ self.render(); // insert into DOM $element.after(self.editorEl); // compile (needed to attach ng-* events from markup) newScope = $scope.$new(); $compile(self.editorEl)(newScope); // attach listeners (`escape`, autosubmit, etc) self.addListeners(); // hide element $element.addClass('editable-hide'); // onshow return self.onshow(); }; //hide self.hide = function() { // destroy the scope to prevent memory leak newScope.$destroy(); self.controlsEl.remove(); self.editorEl.remove(); $element.removeClass('editable-hide'); if (self.popover) { $templateCache.remove('popover.html'); } // onhide return self.onhide(); }; // cancel self.cancel = function() { // oncancel self.oncancel(); // don't call hide() here as it called in form's code }; /* Called after show to attach listeners */ self.addListeners = function() { // bind keyup for `escape` self.inputEl.bind('keyup', function(e) { if(!self.single) { return; } // todo: move this to editable-form! switch(e.keyCode) { // hide on `escape` press case 27: self.scope.$apply(function() { self.scope.$form.$cancel(); }); break; } }); // autosubmit when `no buttons` if (self.single && self.buttons === 'no') { self.autosubmit(); } // click - mark element as clicked to exclude in document click handler self.editorEl.bind('click', function(e) { // ignore right/middle button click if (e.which && e.which !== 1) { return; } if (self.scope.$form.$visible) { self.scope.$form._clicked = true; } }); }; // setWaiting self.setWaiting = function(value) { if (value) { // participate in waiting only if not disabled inWaiting = !self.inputEl.attr('disabled') && !self.inputEl.attr('ng-disabled') && !self.inputEl.attr('ng-enabled'); if (inWaiting) { self.inputEl.attr('disabled', 'disabled'); if(self.buttonsEl) { self.buttonsEl.find('button').attr('disabled', 'disabled'); } } } else { if (inWaiting) { self.inputEl.removeAttr('disabled'); if (self.buttonsEl) { self.buttonsEl.find('button').removeAttr('disabled'); } } } }; self.activate = function(start, end) { setTimeout(function() { var el = self.inputEl[0]; if (editableOptions.activate === 'focus' && el.focus) { if (start !== undefined && start !== "" && el.setSelectionRange) { end = end || start; el.onfocus = function() { setTimeout(function() { try { this.setSelectionRange(start,end); } catch(e) { //do nothing, this input doesn't support setSelectionRange } }.bind(this)); }; } if (self.directiveName == 'editableRadiolist' || self.directiveName == 'editableChecklist' || self.directiveName == 'editableBsdate' || self.directiveName == 'editableTagsInput') { //Set focus to first pristine element in the list el.querySelector('.ng-pristine').focus(); } else { el.focus(); } } else if (editableOptions.activate === 'select') { if (el.select){ el.select(); } else if (el.focus) { el.focus(); } } }, 0); }; self.setError = function(msg) { if(!angular.isObject(msg)) { $scope.$error = $sce.trustAsHtml(msg); self.error = msg; } }; /* Checks that result is string or promise returned string and shows it as error message Applied to onshow, onbeforesave, onaftersave */ self.catchError = function(result, noPromise) { if (angular.isObject(result) && noPromise !== true) { $q.when(result).then( //success and fail handlers are equal angular.bind(this, function(r) { this.catchError(r, true); }), angular.bind(this, function(r) { this.catchError(r, true); }) ); //check $http error } else if (noPromise && angular.isObject(result) && result.status && (result.status !== 200) && result.data && angular.isString(result.data)) { this.setError(result.data); //set result to string: to let form know that there was error result = result.data; } else if (angular.isString(result)) { this.setError(result); } return result; }; self.save = function() { valueGetter.assign($scope.$parent, self.useCopy ? angular.copy(self.scope.$data) : self.scope.$data); // no need to call handleEmpty here as we are watching change of model value // self.handleEmpty(); }; /* attach/detach `editable-empty` class to element */ self.handleEmpty = function() { var val = valueGetter($scope.$parent); var isEmpty = val === null || val === undefined || val === "" || (angular.isArray(val) && val.length === 0); $element.toggleClass('editable-empty', isEmpty); }; /* Called when `buttons = "no"` to submit automatically */ self.autosubmit = angular.noop; self.onshow = angular.noop; self.onhide = angular.noop; self.oncancel = angular.noop; self.onbeforesave = angular.noop; self.onaftersave = angular.noop; } return EditableController; }]); /* editableFactory is used to generate editable directives (see `/directives` folder) Inside it does several things: - detect form for editable element. Form may be one of three types: 1. autogenerated form (for single editable elements) 2. wrapper form (element wrapped by <form> tag) 3. linked form (element has `e-form` attribute pointing to existing form) - attach editableController to element Depends on: editableController, editableFormFactory */ angular.module('xeditable').factory('editableDirectiveFactory', ['$parse', '$compile', 'editableThemes', '$rootScope', '$document', 'editableController', 'editableFormController', 'editableOptions', function($parse, $compile, editableThemes, $rootScope, $document, editableController, editableFormController, editableOptions) { //directive object return function(overwrites) { return { restrict: 'A', scope: true, require: [overwrites.directiveName, '?^form'], controller: editableController, link: function(scope, elem, attrs, ctrl) { // editable controller var eCtrl = ctrl[0]; // form controller var eFormCtrl; // this variable indicates is element is bound to some existing form, // or it's single element who's form will be generated automatically // By default consider single element without any linked form.ß var hasForm = false; // element wrapped by form if (ctrl[1]) { eFormCtrl = ctrl[1]; hasForm = attrs.eSingle === undefined; } else if (attrs.eForm) { // element not wrapped by <form>, but we have `e-form` attr var getter = $parse(attrs.eForm)(scope); if (getter) { // form exists in scope (above), e.g. editable column eFormCtrl = getter; hasForm = true; } else if (elem && typeof elem.parents === "function" && elem.parents().last().find('form[name="'+attrs.eForm+'"]').length) { // form exists below or not exist at all: check document.forms // form is below and not processed yet eFormCtrl = null; hasForm = true; } else { // form exists below or not exist at all: check document.forms for (var i=0; i<$document[0].forms.length;i++) { if ($document[0].forms[i].name === attrs.eForm) { // form is below and not processed yet eFormCtrl = null; hasForm = true; break; } } } } /* if(hasForm && !attrs.eName) { throw 'You should provide `e-name` for editable element inside form!'; } */ //check for `editable-form` attr in form /* if(eFormCtrl && ) { throw 'You should provide `e-name` for editable element inside form!'; } */ // store original props to `parent` before merge angular.forEach(overwrites, function(v, k) { if(eCtrl[k] !== undefined) { eCtrl.parent[k] = eCtrl[k]; } }); // merge overwrites to base editable controller angular.extend(eCtrl, overwrites); // x-editable can be disabled using editableOption or edit-disabled attribute var is_disabled = function() { return angular.isDefined(attrs.editDisabled) ? scope.$eval(attrs.editDisabled) : editableOptions.isDisabled; }; // init editable ctrl eCtrl.init(!hasForm); // publich editable controller as `$editable` to be referenced in html scope.$editable = eCtrl; // add `editable` class to element elem.addClass('editable'); // hasForm if(hasForm) { if(eFormCtrl) { scope.$form = eFormCtrl; if(!scope.$form.$addEditable) { throw 'Form with editable elements should have `editable-form` attribute.'; } scope.$form.$addEditable(eCtrl); } else { // future form (below): add editable controller to buffer and add to form later $rootScope.$$editableBuffer = $rootScope.$$editableBuffer || {}; $rootScope.$$editableBuffer[attrs.eForm] = $rootScope.$$editableBuffer[attrs.eForm] || []; $rootScope.$$editableBuffer[attrs.eForm].push(eCtrl); scope.$form = null; //will be re-assigned later } // !hasForm } else { // create editableform controller scope.$form = editableFor