xeditable.js 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237
  1. /*!
  2. angular-xeditable - 0.1.9
  3. Edit-in-place for angular.js
  4. Build date: 2015-03-22
  5. */
  6. /**
  7. * Angular-xeditable module
  8. *
  9. */
  10. angular.module('xeditable', [])
  11. /**
  12. * Default options.
  13. *
  14. * @namespace editable-options
  15. */
  16. //todo: maybe better have editableDefaults, not options...
  17. .value('editableOptions', {
  18. /**
  19. * Theme. Possible values `bs3`, `bs2`, `default`.
  20. *
  21. * @var {string} theme
  22. * @memberOf editable-options
  23. */
  24. theme: 'default',
  25. /**
  26. * Icon Set. Possible values `font-awesome`, `default`.
  27. *
  28. * @var {string} icon set
  29. * @memberOf editable-options
  30. */
  31. icon_set: 'default',
  32. /**
  33. * Whether to show buttons for single editalbe element.
  34. * Possible values `right` (default), `no`.
  35. *
  36. * @var {string} buttons
  37. * @memberOf editable-options
  38. */
  39. buttons: 'right',
  40. /**
  41. * Default value for `blur` attribute of single editable element.
  42. * Can be `cancel|submit|ignore`.
  43. *
  44. * @var {string} blurElem
  45. * @memberOf editable-options
  46. */
  47. blurElem: 'cancel',
  48. /**
  49. * Default value for `blur` attribute of editable form.
  50. * Can be `cancel|submit|ignore`.
  51. *
  52. * @var {string} blurForm
  53. * @memberOf editable-options
  54. */
  55. blurForm: 'ignore',
  56. /**
  57. * How input elements get activated. Possible values: `focus|select|none`.
  58. *
  59. * @var {string} activate
  60. * @memberOf editable-options
  61. */
  62. activate: 'focus',
  63. /**
  64. * Whether to disable x-editable. Can be overloaded on each element.
  65. *
  66. * @var {boolean} isDisabled
  67. * @memberOf editable-options
  68. */
  69. isDisabled: false,
  70. /**
  71. * Event, on which the edit mode gets activated.
  72. * Can be any event.
  73. *
  74. * @var {string} activationEvent
  75. * @memberOf editable-options
  76. */
  77. activationEvent: 'click'
  78. });
  79. /*
  80. Angular-ui bootstrap datepicker
  81. http://angular-ui.github.io/bootstrap/#/datepicker
  82. */
  83. angular.module('xeditable').directive('editableBsdate', ['editableDirectiveFactory',
  84. function(editableDirectiveFactory) {
  85. return editableDirectiveFactory({
  86. directiveName: 'editableBsdate',
  87. inputTpl: '<div></div>',
  88. render: function() {
  89. /** This basically renders a datepicker as in the example shown in
  90. ** http://angular-ui.github.io/bootstrap/#/datepicker
  91. ** The attributes are all the same as in the bootstrap-ui datepicker with e- as prefix
  92. **/
  93. this.parent.render.call(this);
  94. var inputDatePicker = angular.element('<input type="text" class="form-control" ng-model="$data"/>');
  95. var buttonDatePicker = angular.element('<button type="button" class="btn btn-default"><i class="glyphicon glyphicon-calendar"></i></button>');
  96. var buttonWrapper = angular.element('<span class="input-group-btn"></span>');
  97. inputDatePicker.attr('datepicker-popup', this.attrs.eDatepickerPopupXEditable || 'yyyy/MM/dd' );
  98. inputDatePicker.attr('is-open', this.attrs.eIsOpen);
  99. inputDatePicker.attr('date-disabled', this.attrs.eDateDisabled);
  100. inputDatePicker.attr('datepicker-popup', this.attrs.eDatepickerPopup);
  101. inputDatePicker.attr('datepicker-mode', this.attrs.eDatepickerMode || 'day');
  102. inputDatePicker.attr('min-date', this.attrs.eMinDate);
  103. inputDatePicker.attr('max-date', this.attrs.eMaxDate);
  104. inputDatePicker.attr('show-weeks', this.attrs.eShowWeeks || true);
  105. inputDatePicker.attr('starting-day', this.attrs.eStartingDay || 0);
  106. inputDatePicker.attr('init-date', this.attrs.eInitDate || new Date());
  107. inputDatePicker.attr('min-mode', this.attrs.eMinMode || 'day');
  108. inputDatePicker.attr('max-mode', this.attrs.eMaxMode || 'year');
  109. inputDatePicker.attr('format-day', this.attrs.eFormatDay || 'dd');
  110. inputDatePicker.attr('format-month', this.attrs.eFormatMonth || 'MMMM');
  111. inputDatePicker.attr('format-year', this.attrs.eFormatYear || 'yyyy');
  112. inputDatePicker.attr('format-day-header', this.attrs.eFormatDayHeader || 'EEE');
  113. inputDatePicker.attr('format-day-title', this.attrs.eFormatDayTitle || 'MMMM yyyy');
  114. inputDatePicker.attr('format-month-title', this.attrs.eFormatMonthTitle || 'yyyy');
  115. inputDatePicker.attr('year-range', this.attrs.eYearRange || 20);
  116. inputDatePicker.attr('show-button-bar', this.attrs.eShowButtonBar || true);
  117. inputDatePicker.attr('current-text', this.attrs.eCurrentText || 'Today');
  118. inputDatePicker.attr('clear-text', this.attrs.eClearText || 'Clear');
  119. inputDatePicker.attr('close-text', this.attrs.eCloseText || 'Done');
  120. inputDatePicker.attr('close-on-date-selection', this.attrs.eCloseOnDateSelection || true);
  121. inputDatePicker.attr('date-picker-append-to-body', this.attrs.eDatePickerAppendToBody || false);
  122. inputDatePicker.attr('date-disabled', this.attrs.eDateDisabled);
  123. buttonDatePicker.attr('ng-click',this.attrs.eNgClick);
  124. buttonWrapper.append(buttonDatePicker);
  125. this.inputEl.prepend(inputDatePicker);
  126. this.inputEl.append(buttonWrapper);
  127. this.inputEl.removeAttr('class');
  128. this.inputEl.attr('class','input-group');
  129. }
  130. });
  131. }]);
  132. /*
  133. Angular-ui bootstrap editable timepicker
  134. http://angular-ui.github.io/bootstrap/#/timepicker
  135. */
  136. angular.module('xeditable').directive('editableBstime', ['editableDirectiveFactory',
  137. function(editableDirectiveFactory) {
  138. return editableDirectiveFactory({
  139. directiveName: 'editableBstime',
  140. inputTpl: '<timepicker></timepicker>',
  141. render: function() {
  142. this.parent.render.call(this);
  143. // timepicker can't update model when ng-model set directly to it
  144. // see: https://github.com/angular-ui/bootstrap/issues/1141
  145. // so we wrap it into DIV
  146. var div = angular.element('<div class="well well-small" style="display:inline-block;"></div>');
  147. // move ng-model to wrapping div
  148. div.attr('ng-model', this.inputEl.attr('ng-model'));
  149. this.inputEl.removeAttr('ng-model');
  150. // move ng-change to wrapping div
  151. if(this.attrs.eNgChange) {
  152. div.attr('ng-change', this.inputEl.attr('ng-change'));
  153. this.inputEl.removeAttr('ng-change');
  154. }
  155. // wrap
  156. this.inputEl.wrap(div);
  157. }
  158. });
  159. }]);
  160. //checkbox
  161. angular.module('xeditable').directive('editableCheckbox', ['editableDirectiveFactory',
  162. function(editableDirectiveFactory) {
  163. return editableDirectiveFactory({
  164. directiveName: 'editableCheckbox',
  165. inputTpl: '<input type="checkbox">',
  166. render: function() {
  167. this.parent.render.call(this);
  168. if(this.attrs.eTitle) {
  169. this.inputEl.wrap('<label></label>');
  170. this.inputEl.parent().append(this.attrs.eTitle);
  171. }
  172. },
  173. autosubmit: function() {
  174. var self = this;
  175. self.inputEl.bind('change', function() {
  176. setTimeout(function() {
  177. self.scope.$apply(function() {
  178. self.scope.$form.$submit();
  179. });
  180. }, 500);
  181. });
  182. }
  183. });
  184. }]);
  185. // checklist
  186. angular.module('xeditable').directive('editableChecklist', [
  187. 'editableDirectiveFactory',
  188. 'editableNgOptionsParser',
  189. function(editableDirectiveFactory, editableNgOptionsParser) {
  190. return editableDirectiveFactory({
  191. directiveName: 'editableChecklist',
  192. inputTpl: '<span></span>',
  193. useCopy: true,
  194. render: function() {
  195. this.parent.render.call(this);
  196. var parsed = editableNgOptionsParser(this.attrs.eNgOptions);
  197. var html = '<label ng-repeat="'+parsed.ngRepeat+'">'+
  198. '<input type="checkbox" checklist-model="$parent.$data" checklist-value="'+parsed.locals.valueFn+'">'+
  199. '<span ng-bind="'+parsed.locals.displayFn+'"></span></label>';
  200. this.inputEl.removeAttr('ng-model');
  201. this.inputEl.removeAttr('ng-options');
  202. this.inputEl.html(html);
  203. }
  204. });
  205. }]);
  206. angular.module('xeditable').directive('editableCombodate', ['editableDirectiveFactory', 'editableCombodate',
  207. function(editableDirectiveFactory, editableCombodate) {
  208. return editableDirectiveFactory({
  209. directiveName: 'editableCombodate',
  210. inputTpl: '<input type="text">',
  211. render: function() {
  212. this.parent.render.call(this);
  213. var combodate = editableCombodate.getInstance(this.inputEl, {value: new Date(this.scope.$data)});
  214. var self = this;
  215. combodate.$widget.find('select').bind('change', function(e) {
  216. self.scope.$data = (new Date(combodate.getValue())).toISOString();
  217. });
  218. }
  219. });
  220. }
  221. ]);
  222. /*
  223. Input types: text|email|tel|number|url|search|color|date|datetime|time|month|week
  224. */
  225. (function() {
  226. var types = 'text|password|email|tel|number|url|search|color|date|datetime|time|month|week|file'.split('|');
  227. //todo: datalist
  228. // generate directives
  229. angular.forEach(types, function(type) {
  230. var directiveName = 'editable'+type.charAt(0).toUpperCase() + type.slice(1);
  231. angular.module('xeditable').directive(directiveName, ['editableDirectiveFactory',
  232. function(editableDirectiveFactory) {
  233. return editableDirectiveFactory({
  234. directiveName: directiveName,
  235. inputTpl: '<input type="'+type+'">'
  236. });
  237. }]);
  238. });
  239. //`range` is bit specific
  240. angular.module('xeditable').directive('editableRange', ['editableDirectiveFactory',
  241. function(editableDirectiveFactory) {
  242. return editableDirectiveFactory({
  243. directiveName: 'editableRange',
  244. inputTpl: '<input type="range" id="range" name="range">',
  245. render: function() {
  246. this.parent.render.call(this);
  247. this.inputEl.after('<output>{{$data}}</output>');
  248. }
  249. });
  250. }]);
  251. }());
  252. // radiolist
  253. angular.module('xeditable').directive('editableRadiolist', [
  254. 'editableDirectiveFactory',
  255. 'editableNgOptionsParser',
  256. function(editableDirectiveFactory, editableNgOptionsParser) {
  257. return editableDirectiveFactory({
  258. directiveName: 'editableRadiolist',
  259. inputTpl: '<span></span>',
  260. render: function() {
  261. this.parent.render.call(this);
  262. var parsed = editableNgOptionsParser(this.attrs.eNgOptions);
  263. var html = '<label ng-repeat="'+parsed.ngRepeat+'">'+
  264. '<input type="radio" ng-disabled="' + this.attrs.eNgDisabled + '" ng-model="$parent.$data" value="{{'+parsed.locals.valueFn+'}}">'+
  265. '<span ng-bind="'+parsed.locals.displayFn+'"></span></label>';
  266. this.inputEl.removeAttr('ng-model');
  267. this.inputEl.removeAttr('ng-options');
  268. this.inputEl.html(html);
  269. },
  270. autosubmit: function() {
  271. var self = this;
  272. self.inputEl.bind('change', function() {
  273. setTimeout(function() {
  274. self.scope.$apply(function() {
  275. self.scope.$form.$submit();
  276. });
  277. }, 500);
  278. });
  279. }
  280. });
  281. }]);
  282. //select
  283. angular.module('xeditable').directive('editableSelect', ['editableDirectiveFactory',
  284. function(editableDirectiveFactory) {
  285. return editableDirectiveFactory({
  286. directiveName: 'editableSelect',
  287. inputTpl: '<select></select>',
  288. autosubmit: function() {
  289. var self = this;
  290. self.inputEl.bind('change', function() {
  291. self.scope.$apply(function() {
  292. self.scope.$form.$submit();
  293. });
  294. });
  295. }
  296. });
  297. }]);
  298. //textarea
  299. angular.module('xeditable').directive('editableTextarea', ['editableDirectiveFactory',
  300. function(editableDirectiveFactory) {
  301. return editableDirectiveFactory({
  302. directiveName: 'editableTextarea',
  303. inputTpl: '<textarea></textarea>',
  304. addListeners: function() {
  305. var self = this;
  306. self.parent.addListeners.call(self);
  307. // submit textarea by ctrl+enter even with buttons
  308. if (self.single && self.buttons !== 'no') {
  309. self.autosubmit();
  310. }
  311. },
  312. autosubmit: function() {
  313. var self = this;
  314. self.inputEl.bind('keydown', function(e) {
  315. if ((e.ctrlKey || e.metaKey) && (e.keyCode === 13)) {
  316. self.scope.$apply(function() {
  317. self.scope.$form.$submit();
  318. });
  319. }
  320. });
  321. }
  322. });
  323. }]);
  324. /**
  325. * EditableController class.
  326. * Attached to element with `editable-xxx` directive.
  327. *
  328. * @namespace editable-element
  329. */
  330. /*
  331. TODO: this file should be refactored to work more clear without closures!
  332. */
  333. angular.module('xeditable').factory('editableController',
  334. ['$q', 'editableUtils',
  335. function($q, editableUtils) {
  336. //EditableController function
  337. EditableController.$inject = ['$scope', '$attrs', '$element', '$parse', 'editableThemes', 'editableIcons', 'editableOptions', '$rootScope', '$compile', '$q'];
  338. function EditableController($scope, $attrs, $element, $parse, editableThemes, editableIcons, editableOptions, $rootScope, $compile, $q) {
  339. var valueGetter;
  340. //if control is disabled - it does not participate in waiting process
  341. var inWaiting;
  342. var self = this;
  343. self.scope = $scope;
  344. self.elem = $element;
  345. self.attrs = $attrs;
  346. self.inputEl = null;
  347. self.editorEl = null;
  348. self.single = true;
  349. self.error = '';
  350. self.theme = editableThemes[editableOptions.theme] || editableThemes['default'];
  351. self.parent = {};
  352. //will be undefined if icon_set is default and theme is default
  353. self.icon_set = editableOptions.icon_set === 'default' ? editableIcons.default[editableOptions.theme] : editableIcons.external[editableOptions.icon_set];
  354. //to be overwritten by directive
  355. self.inputTpl = '';
  356. self.directiveName = '';
  357. // with majority of controls copy is not needed, but..
  358. // copy MUST NOT be used for `select-multiple` with objects as items
  359. // copy MUST be used for `checklist`
  360. self.useCopy = false;
  361. //runtime (defaults)
  362. self.single = null;
  363. /**
  364. * Attributes defined with `e-*` prefix automatically transfered from original element to
  365. * control.
  366. * For example, if you set `<span editable-text="user.name" e-style="width: 100px"`>
  367. * then input will appear as `<input style="width: 100px">`.
  368. * See [demo](#text-customize).
  369. *
  370. * @var {any|attribute} e-*
  371. * @memberOf editable-element
  372. */
  373. /**
  374. * Whether to show ok/cancel buttons. Values: `right|no`.
  375. * If set to `no` control automatically submitted when value changed.
  376. * If control is part of form buttons will never be shown.
  377. *
  378. * @var {string|attribute} buttons
  379. * @memberOf editable-element
  380. */
  381. self.buttons = 'right';
  382. /**
  383. * Action when control losses focus. Values: `cancel|submit|ignore`.
  384. * Has sense only for single editable element.
  385. * Otherwise, if control is part of form - you should set `blur` of form, not of individual element.
  386. *
  387. * @var {string|attribute} blur
  388. * @memberOf editable-element
  389. */
  390. // no real `blur` property as it is transfered to editable form
  391. //init
  392. self.init = function(single) {
  393. self.single = single;
  394. self.name = $attrs.eName || $attrs[self.directiveName];
  395. /*
  396. if(!$attrs[directiveName] && !$attrs.eNgModel && ($attrs.eValue === undefined)) {
  397. throw 'You should provide value for `'+directiveName+'` or `e-value` in editable element!';
  398. }
  399. */
  400. if($attrs[self.directiveName]) {
  401. valueGetter = $parse($attrs[self.directiveName]);
  402. } else {
  403. throw 'You should provide value for `'+self.directiveName+'` in editable element!';
  404. }
  405. // settings for single and non-single
  406. if (!self.single) {
  407. // hide buttons for non-single
  408. self.buttons = 'no';
  409. } else {
  410. self.buttons = self.attrs.buttons || editableOptions.buttons;
  411. }
  412. //if name defined --> watch changes and update $data in form
  413. if($attrs.eName) {
  414. self.scope.$watch('$data', function(newVal){
  415. self.scope.$form.$data[$attrs.eName] = newVal;
  416. });
  417. }
  418. /**
  419. * Called when control is shown.
  420. * See [demo](#select-remote).
  421. *
  422. * @var {method|attribute} onshow
  423. * @memberOf editable-element
  424. */
  425. if($attrs.onshow) {
  426. self.onshow = function() {
  427. return self.catchError($parse($attrs.onshow)($scope));
  428. };
  429. }
  430. /**
  431. * Called when control is hidden after both save or cancel.
  432. *
  433. * @var {method|attribute} onhide
  434. * @memberOf editable-element
  435. */
  436. if($attrs.onhide) {
  437. self.onhide = function() {
  438. return $parse($attrs.onhide)($scope);
  439. };
  440. }
  441. /**
  442. * Called when control is cancelled.
  443. *
  444. * @var {method|attribute} oncancel
  445. * @memberOf editable-element
  446. */
  447. if($attrs.oncancel) {
  448. self.oncancel = function() {
  449. return $parse($attrs.oncancel)($scope);
  450. };
  451. }
  452. /**
  453. * Called during submit before value is saved to model.
  454. * See [demo](#onbeforesave).
  455. *
  456. * @var {method|attribute} onbeforesave
  457. * @memberOf editable-element
  458. */
  459. if ($attrs.onbeforesave) {
  460. self.onbeforesave = function() {
  461. return self.catchError($parse($attrs.onbeforesave)($scope));
  462. };
  463. }
  464. /**
  465. * Called during submit after value is saved to model.
  466. * See [demo](#onaftersave).
  467. *
  468. * @var {method|attribute} onaftersave
  469. * @memberOf editable-element
  470. */
  471. if ($attrs.onaftersave) {
  472. self.onaftersave = function() {
  473. return self.catchError($parse($attrs.onaftersave)($scope));
  474. };
  475. }
  476. // watch change of model to update editable element
  477. // now only add/remove `editable-empty` class.
  478. // Initially this method called with newVal = undefined, oldVal = undefined
  479. // so no need initially call handleEmpty() explicitly
  480. $scope.$parent.$watch($attrs[self.directiveName], function(newVal, oldVal) {
  481. self.setLocalValue();
  482. self.handleEmpty();
  483. });
  484. };
  485. self.render = function() {
  486. var theme = self.theme;
  487. //build input
  488. self.inputEl = angular.element(self.inputTpl);
  489. //build controls
  490. self.controlsEl = angular.element(theme.controlsTpl);
  491. self.controlsEl.append(self.inputEl);
  492. //build buttons
  493. if(self.buttons !== 'no') {
  494. self.buttonsEl = angular.element(theme.buttonsTpl);
  495. self.submitEl = angular.element(theme.submitTpl);
  496. self.cancelEl = angular.element(theme.cancelTpl);
  497. if(self.icon_set) {
  498. self.submitEl.find('span').addClass(self.icon_set.ok);
  499. self.cancelEl.find('span').addClass(self.icon_set.cancel);
  500. }
  501. self.buttonsEl.append(self.submitEl).append(self.cancelEl);
  502. self.controlsEl.append(self.buttonsEl);
  503. self.inputEl.addClass('editable-has-buttons');
  504. }
  505. //build error
  506. self.errorEl = angular.element(theme.errorTpl);
  507. self.controlsEl.append(self.errorEl);
  508. //build editor
  509. self.editorEl = angular.element(self.single ? theme.formTpl : theme.noformTpl);
  510. self.editorEl.append(self.controlsEl);
  511. // transfer `e-*|data-e-*|x-e-*` attributes
  512. for(var k in $attrs.$attr) {
  513. if(k.length <= 1) {
  514. continue;
  515. }
  516. var transferAttr = false;
  517. var nextLetter = k.substring(1, 2);
  518. // if starts with `e` + uppercase letter
  519. if(k.substring(0, 1) === 'e' && nextLetter === nextLetter.toUpperCase()) {
  520. transferAttr = k.substring(1); // cut `e`
  521. } else {
  522. continue;
  523. }
  524. // exclude `form` and `ng-submit`,
  525. if(transferAttr === 'Form' || transferAttr === 'NgSubmit') {
  526. continue;
  527. }
  528. // convert back to lowercase style
  529. transferAttr = transferAttr.substring(0, 1).toLowerCase() + editableUtils.camelToDash(transferAttr.substring(1));
  530. // workaround for attributes without value (e.g. `multiple = "multiple"`)
  531. // except for 'e-value'
  532. var attrValue = (transferAttr !== 'value' && $attrs[k] === '') ? transferAttr : $attrs[k];
  533. // set attributes to input
  534. self.inputEl.attr(transferAttr, attrValue);
  535. }
  536. self.inputEl.addClass('editable-input');
  537. self.inputEl.attr('ng-model', '$parent.$data');
  538. // add directiveName class to editor, e.g. `editable-text`
  539. self.editorEl.addClass(editableUtils.camelToDash(self.directiveName));
  540. if(self.single) {
  541. self.editorEl.attr('editable-form', '$form');
  542. // transfer `blur` to form
  543. self.editorEl.attr('blur', self.attrs.blur || (self.buttons === 'no' ? 'cancel' : editableOptions.blurElem));
  544. }
  545. //apply `postrender` method of theme
  546. if(angular.isFunction(theme.postrender)) {
  547. theme.postrender.call(self);
  548. }
  549. };
  550. // with majority of controls copy is not needed, but..
  551. // copy MUST NOT be used for `select-multiple` with objects as items
  552. // copy MUST be used for `checklist`
  553. self.setLocalValue = function() {
  554. self.scope.$data = self.useCopy ?
  555. angular.copy(valueGetter($scope.$parent)) :
  556. valueGetter($scope.$parent);
  557. };
  558. var newScope = null;
  559. //show
  560. self.show = function() {
  561. // set value of scope.$data
  562. self.setLocalValue();
  563. /*
  564. Originally render() was inside init() method, but some directives polluting editorEl,
  565. so it is broken on second openning.
  566. Cloning is not a solution as jqLite can not clone with event handler's.
  567. */
  568. self.render();
  569. // insert into DOM
  570. $element.after(self.editorEl);
  571. //create new scope
  572. newScope = $scope.$new();
  573. // compile (needed to attach ng-* events from markup)
  574. $compile(self.editorEl)(newScope);
  575. // attach listeners (`escape`, autosubmit, etc)
  576. self.addListeners();
  577. // hide element
  578. $element.addClass('editable-hide');
  579. // onshow
  580. return self.onshow();
  581. };
  582. //hide
  583. self.hide = function() {
  584. newScope.$destroy();
  585. self.editorEl.remove();
  586. $element.removeClass('editable-hide');
  587. // onhide
  588. return self.onhide();
  589. };
  590. // cancel
  591. self.cancel = function() {
  592. // oncancel
  593. self.oncancel();
  594. // don't call hide() here as it called in form's code
  595. };
  596. /*
  597. Called after show to attach listeners
  598. */
  599. self.addListeners = function() {
  600. // bind keyup for `escape`
  601. self.inputEl.bind('keyup', function(e) {
  602. if(!self.single) {
  603. return;
  604. }
  605. // todo: move this to editable-form!
  606. switch(e.keyCode) {
  607. // hide on `escape` press
  608. case 27:
  609. self.scope.$apply(function() {
  610. self.scope.$form.$cancel();
  611. });
  612. break;
  613. }
  614. });
  615. // autosubmit when `no buttons`
  616. if (self.single && self.buttons === 'no') {
  617. self.autosubmit();
  618. }
  619. // click - mark element as clicked to exclude in document click handler
  620. self.editorEl.bind('click', function(e) {
  621. // ignore right/middle button click
  622. if (e.which && e.which !== 1) {
  623. return;
  624. }
  625. if (self.scope.$form.$visible) {
  626. self.scope.$form._clicked = true;
  627. }
  628. });
  629. };
  630. // setWaiting
  631. self.setWaiting = function(value) {
  632. if (value) {
  633. // participate in waiting only if not disabled
  634. inWaiting = !self.inputEl.attr('disabled') &&
  635. !self.inputEl.attr('ng-disabled') &&
  636. !self.inputEl.attr('ng-enabled');
  637. if (inWaiting) {
  638. self.inputEl.attr('disabled', 'disabled');
  639. if(self.buttonsEl) {
  640. self.buttonsEl.find('button').attr('disabled', 'disabled');
  641. }
  642. }
  643. } else {
  644. if (inWaiting) {
  645. self.inputEl.removeAttr('disabled');
  646. if (self.buttonsEl) {
  647. self.buttonsEl.find('button').removeAttr('disabled');
  648. }
  649. }
  650. }
  651. };
  652. self.activate = function(start, end) {
  653. setTimeout(function() {
  654. var el = self.inputEl[0];
  655. if (editableOptions.activate === 'focus' && el.focus) {
  656. if(start){
  657. end = end || start;
  658. el.onfocus = function(){
  659. var that = this;
  660. setTimeout(function(){
  661. that.setSelectionRange(start,end);
  662. });
  663. };
  664. }
  665. el.focus();
  666. }
  667. if (editableOptions.activate === 'select' && el.select) {
  668. el.select();
  669. }
  670. }, 0);
  671. };
  672. self.setError = function(msg) {
  673. if(!angular.isObject(msg)) {
  674. $scope.$error = msg;
  675. self.error = msg;
  676. }
  677. };
  678. /*
  679. Checks that result is string or promise returned string and shows it as error message
  680. Applied to onshow, onbeforesave, onaftersave
  681. */
  682. self.catchError = function(result, noPromise) {
  683. if (angular.isObject(result) && noPromise !== true) {
  684. $q.when(result).then(
  685. //success and fail handlers are equal
  686. angular.bind(this, function(r) {
  687. this.catchError(r, true);
  688. }),
  689. angular.bind(this, function(r) {
  690. this.catchError(r, true);
  691. })
  692. );
  693. //check $http error
  694. } else if (noPromise && angular.isObject(result) && result.status &&
  695. (result.status !== 200) && result.data && angular.isString(result.data)) {
  696. this.setError(result.data);
  697. //set result to string: to let form know that there was error
  698. result = result.data;
  699. } else if (angular.isString(result)) {
  700. this.setError(result);
  701. }
  702. return result;
  703. };
  704. self.save = function() {
  705. valueGetter.assign($scope.$parent,
  706. self.useCopy ? angular.copy(self.scope.$data) : self.scope.$data);
  707. // no need to call handleEmpty here as we are watching change of model value
  708. // self.handleEmpty();
  709. };
  710. /*
  711. attach/detach `editable-empty` class to element
  712. */
  713. self.handleEmpty = function() {
  714. var val = valueGetter($scope.$parent);
  715. var isEmpty = val === null || val === undefined || val === "" || (angular.isArray(val) && val.length === 0);
  716. $element.toggleClass('editable-empty', isEmpty);
  717. };
  718. /*
  719. Called when `buttons = "no"` to submit automatically
  720. */
  721. self.autosubmit = angular.noop;
  722. self.onshow = angular.noop;
  723. self.onhide = angular.noop;
  724. self.oncancel = angular.noop;
  725. self.onbeforesave = angular.noop;
  726. self.onaftersave = angular.noop;
  727. }
  728. return EditableController;
  729. }]);
  730. /*
  731. editableFactory is used to generate editable directives (see `/directives` folder)
  732. Inside it does several things:
  733. - detect form for editable element. Form may be one of three types:
  734. 1. autogenerated form (for single editable elements)
  735. 2. wrapper form (element wrapped by <form> tag)
  736. 3. linked form (element has `e-form` attribute pointing to existing form)
  737. - attach editableController to element
  738. Depends on: editableController, editableFormFactory
  739. */
  740. angular.module('xeditable').factory('editableDirectiveFactory',
  741. ['$parse', '$compile', 'editableThemes', '$rootScope', '$document', 'editableController', 'editableFormController', 'editableOptions',
  742. function($parse, $compile, editableThemes, $rootScope, $document, editableController, editableFormController, editableOptions) {
  743. //directive object
  744. return function(overwrites) {
  745. return {
  746. restrict: 'A',
  747. scope: true,
  748. require: [overwrites.directiveName, '?^form'],
  749. controller: editableController,
  750. link: function(scope, elem, attrs, ctrl) {
  751. // editable controller
  752. var eCtrl = ctrl[0];
  753. // form controller
  754. var eFormCtrl;
  755. // this variable indicates is element is bound to some existing form,
  756. // or it's single element who's form will be generated automatically
  757. // By default consider single element without any linked form.ß
  758. var hasForm = false;
  759. // element wrapped by form
  760. if(ctrl[1]) {
  761. eFormCtrl = ctrl[1];
  762. hasForm = true;
  763. } else if(attrs.eForm) { // element not wrapped by <form>, but we hane `e-form` attr
  764. var getter = $parse(attrs.eForm)(scope);
  765. if(getter) { // form exists in scope (above), e.g. editable column
  766. eFormCtrl = getter;
  767. hasForm = true;
  768. } else { // form exists below or not exist at all: check document.forms
  769. for(var i=0; i<$document[0].forms.length;i++){
  770. if($document[0].forms[i].name === attrs.eForm) {
  771. // form is below and not processed yet
  772. eFormCtrl = null;
  773. hasForm = true;
  774. break;
  775. }
  776. }
  777. }
  778. }
  779. /*
  780. if(hasForm && !attrs.eName) {
  781. throw 'You should provide `e-name` for editable element inside form!';
  782. }
  783. */
  784. //check for `editable-form` attr in form
  785. /*
  786. if(eFormCtrl && ) {
  787. throw 'You should provide `e-name` for editable element inside form!';
  788. }
  789. */
  790. // store original props to `parent` before merge
  791. angular.forEach(overwrites, function(v, k) {
  792. if(eCtrl[k] !== undefined) {
  793. eCtrl.parent[k] = eCtrl[k];
  794. }
  795. });
  796. // merge overwrites to base editable controller
  797. angular.extend(eCtrl, overwrites);
  798. // x-editable can be disabled using editableOption or edit-disabled attribute
  799. var disabled = angular.isDefined(attrs.editDisabled) ?
  800. scope.$eval(attrs.editDisabled) :
  801. editableOptions.isDisabled;
  802. if (disabled) {
  803. return;
  804. }
  805. // init editable ctrl
  806. eCtrl.init(!hasForm);
  807. // publich editable controller as `$editable` to be referenced in html
  808. scope.$editable = eCtrl;
  809. // add `editable` class to element
  810. elem.addClass('editable');
  811. // hasForm
  812. if(hasForm) {
  813. if(eFormCtrl) {
  814. scope.$form = eFormCtrl;
  815. if(!scope.$form.$addEditable) {
  816. throw 'Form with editable elements should have `editable-form` attribute.';
  817. }
  818. scope.$form.$addEditable(eCtrl);
  819. } else {
  820. // future form (below): add editable controller to buffer and add to form later
  821. $rootScope.$$editableBuffer = $rootScope.$$editableBuffer || {};
  822. $rootScope.$$editableBuffer[attrs.eForm] = $rootScope.$$editableBuffer[attrs.eForm] || [];
  823. $rootScope.$$editableBuffer[attrs.eForm].push(eCtrl);
  824. scope.$form = null; //will be re-assigned later
  825. }
  826. // !hasForm
  827. } else {
  828. // create editableform controller
  829. scope.$form = editableFormController();
  830. // add self to editable controller
  831. scope.$form.$addEditable(eCtrl);
  832. // if `e-form` provided, publish local $form in scope
  833. if(attrs.eForm) {
  834. $parse(attrs.eForm).assign(scope, scope.$form);
  835. }
  836. // bind click - if no external form defined
  837. if(!attrs.eForm || attrs.eClickable) {
  838. elem.addClass('editable-click');
  839. elem.bind(editableOptions.activationEvent, function(e) {
  840. e.preventDefault();
  841. e.editable = eCtrl;
  842. scope.$apply(function(){
  843. scope.$form.$show();
  844. });
  845. });
  846. }
  847. }
  848. }
  849. };
  850. };
  851. }]);
  852. /*
  853. Returns editableForm controller
  854. */
  855. angular.module('xeditable').factory('editableFormController',
  856. ['$parse', '$document', '$rootScope', 'editablePromiseCollection', 'editableUtils',
  857. function($parse, $document, $rootScope, editablePromiseCollection, editableUtils) {
  858. // array of opened editable forms
  859. var shown = [];
  860. //Check if the child element correspond or is a descendant of the parent element
  861. var isSelfOrDescendant = function (parent, child) {
  862. if (child == parent) {
  863. return true;
  864. }
  865. var node = child.parentNode;
  866. while (node !== null) {
  867. if (node == parent) {
  868. return true;
  869. }
  870. node = node.parentNode;
  871. }
  872. return false;
  873. };
  874. //Check if it is a real blur : if the click event appear on a shown editable elem, this is not a blur.
  875. var isBlur = function(shown, event) {
  876. var isBlur = true;
  877. var editables = shown.$editables;
  878. angular.forEach(editables, function(v){
  879. var element = v.editorEl[0];
  880. if (isSelfOrDescendant(element, event.target))
  881. isBlur = false;
  882. });
  883. return isBlur;
  884. };
  885. // bind click to body: cancel|submit|ignore forms
  886. $document.bind('click', function(e) {
  887. // ignore right/middle button click
  888. if ((e.which && e.which !== 1) || e.isDefaultPrevented()) {
  889. return;
  890. }
  891. var toCancel = [];
  892. var toSubmit = [];
  893. for (var i=0; i<shown.length; i++) {
  894. // exclude clicked
  895. if (shown[i]._clicked) {
  896. shown[i]._clicked = false;
  897. continue;
  898. }
  899. // exclude waiting
  900. if (shown[i].$waiting) {
  901. continue;
  902. }
  903. if (shown[i]._blur === 'cancel' && isBlur(shown[i], e)) {
  904. toCancel.push(shown[i]);
  905. }
  906. if (shown[i]._blur === 'submit' && isBlur(shown[i], e)) {
  907. toSubmit.push(shown[i]);
  908. }
  909. }
  910. if (toCancel.length || toSubmit.length) {
  911. $rootScope.$apply(function() {
  912. angular.forEach(toCancel, function(v){ v.$cancel(); });
  913. angular.forEach(toSubmit, function(v){ v.$submit(); });
  914. });
  915. }
  916. });
  917. var base = {
  918. $addEditable: function(editable) {
  919. //console.log('add editable', editable.elem, editable.elem.bind);
  920. this.$editables.push(editable);
  921. //'on' is not supported in angular 1.0.8
  922. editable.elem.bind('$destroy', angular.bind(this, this.$removeEditable, editable));
  923. //bind editable's local $form to self (if not bound yet, below form)
  924. if (!editable.scope.$form) {
  925. editable.scope.$form = this;
  926. }
  927. //if form already shown - call show() of new editable
  928. if (this.$visible) {
  929. editable.catchError(editable.show());
  930. }
  931. },
  932. $removeEditable: function(editable) {
  933. //arrayRemove
  934. for(var i=0; i < this.$editables.length; i++) {
  935. if(this.$editables[i] === editable) {
  936. this.$editables.splice(i, 1);
  937. return;
  938. }
  939. }
  940. },
  941. /**
  942. * Shows form with editable controls.
  943. *
  944. * @method $show()
  945. * @memberOf editable-form
  946. */
  947. $show: function() {
  948. if (this.$visible) {
  949. return;
  950. }
  951. this.$visible = true;
  952. var pc = editablePromiseCollection();
  953. //own show
  954. pc.when(this.$onshow());
  955. //clear errors
  956. this.$setError(null, '');
  957. //children show
  958. angular.forEach(this.$editables, function(editable) {
  959. pc.when(editable.show());
  960. });
  961. //wait promises and activate
  962. pc.then({
  963. onWait: angular.bind(this, this.$setWaiting),
  964. onTrue: angular.bind(this, this.$activate),
  965. onFalse: angular.bind(this, this.$activate),
  966. onString: angular.bind(this, this.$activate)
  967. });
  968. // add to internal list of shown forms
  969. // setTimeout needed to prevent closing right after opening (e.g. when trigger by button)
  970. setTimeout(angular.bind(this, function() {
  971. // clear `clicked` to get ready for clicks on visible form
  972. this._clicked = false;
  973. if(editableUtils.indexOf(shown, this) === -1) {
  974. shown.push(this);
  975. }
  976. }), 0);
  977. },
  978. /**
  979. * Sets focus on form field specified by `name`.
  980. *
  981. * @method $activate(name)
  982. * @param {string} name name of field
  983. * @memberOf editable-form
  984. */
  985. $activate: function(name) {
  986. var i;
  987. if (this.$editables.length) {
  988. //activate by name
  989. if (angular.isString(name)) {
  990. for(i=0; i<this.$editables.length; i++) {
  991. if (this.$editables[i].name === name) {
  992. this.$editables[i].activate();
  993. return;
  994. }
  995. }
  996. }
  997. //try activate error field
  998. for(i=0; i<this.$editables.length; i++) {
  999. if (this.$editables[i].error) {
  1000. this.$editables[i].activate();
  1001. return;
  1002. }
  1003. }
  1004. //by default activate first field
  1005. this.$editables[0].activate(this.$editables[0].elem[0].selectionStart, this.$editables[0].elem[0].selectionEnd);
  1006. }
  1007. },
  1008. /**
  1009. * Hides form with editable controls without saving.
  1010. *
  1011. * @method $hide()
  1012. * @memberOf editable-form
  1013. */
  1014. $hide: function() {
  1015. if (!this.$visible) {
  1016. return;
  1017. }
  1018. this.$visible = false;
  1019. // self hide
  1020. this.$onhide();
  1021. // children's hide
  1022. angular.forEach(this.$editables, function(editable) {
  1023. editable.hide();
  1024. });
  1025. // remove from internal list of shown forms
  1026. editableUtils.arrayRemove(shown, this);
  1027. },
  1028. /**
  1029. * Triggers `oncancel` event and calls `$hide()`.
  1030. *
  1031. * @method $cancel()
  1032. * @memberOf editable-form
  1033. */
  1034. $cancel: function() {
  1035. if (!this.$visible) {
  1036. return;
  1037. }
  1038. // self cancel
  1039. this.$oncancel();
  1040. // children's cancel
  1041. angular.forEach(this.$editables, function(editable) {
  1042. editable.cancel();
  1043. });
  1044. // self hide
  1045. var that = this;
  1046. setTimeout(function(){
  1047. that.$hide();
  1048. });
  1049. },
  1050. $setWaiting: function(value) {
  1051. this.$waiting = !!value;
  1052. // we can't just set $waiting variable and use it via ng-disabled in children
  1053. // because in editable-row form is not accessible
  1054. angular.forEach(this.$editables, function(editable) {
  1055. editable.setWaiting(!!value);
  1056. });
  1057. },
  1058. /**
  1059. * Shows error message for particular field.
  1060. *
  1061. * @method $setError(name, msg)
  1062. * @param {string} name name of field
  1063. * @param {string} msg error message
  1064. * @memberOf editable-form
  1065. */
  1066. $setError: function(name, msg) {
  1067. angular.forEach(this.$editables, function(editable) {
  1068. if(!name || editable.name === name) {
  1069. editable.setError(msg);
  1070. }
  1071. });
  1072. },
  1073. $submit: function() {
  1074. if (this.$waiting) {
  1075. return;
  1076. }
  1077. //clear errors
  1078. this.$setError(null, '');
  1079. //children onbeforesave
  1080. var pc = editablePromiseCollection();
  1081. angular.forEach(this.$editables, function(editable) {
  1082. pc.when(editable.onbeforesave());
  1083. });
  1084. /*
  1085. onbeforesave result:
  1086. - true/undefined: save data and close form
  1087. - false: close form without saving
  1088. - string: keep form open and show error
  1089. */
  1090. pc.then({
  1091. onWait: angular.bind(this, this.$setWaiting),
  1092. onTrue: angular.bind(this, checkSelf, true),
  1093. onFalse: angular.bind(this, checkSelf, false),
  1094. onString: angular.bind(this, this.$activate)
  1095. });
  1096. //save
  1097. function checkSelf(childrenTrue){
  1098. var pc = editablePromiseCollection();
  1099. pc.when(this.$onbeforesave());
  1100. pc.then({
  1101. onWait: angular.bind(this, this.$setWaiting),
  1102. onTrue: childrenTrue ? angular.bind(this, this.$save) : angular.bind(this, this.$hide),
  1103. onFalse: angular.bind(this, this.$hide),
  1104. onString: angular.bind(this, this.$activate)
  1105. });
  1106. }
  1107. },
  1108. $save: function() {
  1109. // write model for each editable
  1110. angular.forEach(this.$editables, function(editable) {
  1111. editable.save();
  1112. });
  1113. //call onaftersave of self and children
  1114. var pc = editablePromiseCollection();
  1115. pc.when(this.$onaftersave());
  1116. angular.forEach(this.$editables, function(editable) {
  1117. pc.when(editable.onaftersave());
  1118. });
  1119. /*
  1120. onaftersave result:
  1121. - true/undefined/false: just close form
  1122. - string: keep form open and show error
  1123. */
  1124. pc.then({
  1125. onWait: angular.bind(this, this.$setWaiting),
  1126. onTrue: angular.bind(this, this.$hide),
  1127. onFalse: angular.bind(this, this.$hide),
  1128. onString: angular.bind(this, this.$activate)
  1129. });
  1130. },
  1131. $onshow: angular.noop,
  1132. $oncancel: angular.noop,
  1133. $onhide: angular.noop,
  1134. $onbeforesave: angular.noop,
  1135. $onaftersave: angular.noop
  1136. };
  1137. return function() {
  1138. return angular.extend({
  1139. $editables: [],
  1140. /**
  1141. * Form visibility flag.
  1142. *
  1143. * @var {bool} $visible
  1144. * @memberOf editable-form
  1145. */
  1146. $visible: false,
  1147. /**
  1148. * Form waiting flag. It becomes `true` when form is loading or saving data.
  1149. *
  1150. * @var {bool} $waiting
  1151. * @memberOf editable-form
  1152. */
  1153. $waiting: false,
  1154. $data: {},
  1155. _clicked: false,
  1156. _blur: null
  1157. }, base);
  1158. };
  1159. }]);
  1160. /**
  1161. * EditableForm directive. Should be defined in <form> containing editable controls.
  1162. * It add some usefull methods to form variable exposed to scope by `name="myform"` attribute.
  1163. *
  1164. * @namespace editable-form
  1165. */
  1166. angular.module('xeditable').directive('editableForm',
  1167. ['$rootScope', '$parse', 'editableFormController', 'editableOptions',
  1168. function($rootScope, $parse, editableFormController, editableOptions) {
  1169. return {
  1170. restrict: 'A',
  1171. require: ['form'],
  1172. //require: ['form', 'editableForm'],
  1173. //controller: EditableFormController,
  1174. compile: function() {
  1175. return {
  1176. pre: function(scope, elem, attrs, ctrl) {
  1177. var form = ctrl[0];
  1178. var eForm;
  1179. //if `editableForm` has value - publish smartly under this value
  1180. //this is required only for single editor form that is created and removed
  1181. if(attrs.editableForm) {
  1182. if(scope[attrs.editableForm] && scope[attrs.editableForm].$show) {
  1183. eForm = scope[attrs.editableForm];
  1184. angular.extend(form, eForm);
  1185. } else {
  1186. eForm = editableFormController();
  1187. scope[attrs.editableForm] = eForm;
  1188. angular.extend(eForm, form);
  1189. }
  1190. } else { //just merge to form and publish if form has name
  1191. eForm = editableFormController();
  1192. angular.extend(form, eForm);
  1193. }
  1194. //read editables from buffer (that appeared before FORM tag)
  1195. var buf = $rootScope.$$editableBuffer;
  1196. var name = form.$name;
  1197. if(name && buf && buf[name]) {
  1198. angular.forEach(buf[name], function(editable) {
  1199. eForm.$addEditable(editable);
  1200. });
  1201. delete buf[name];
  1202. }
  1203. },
  1204. post: function(scope, elem, attrs, ctrl) {
  1205. var eForm;
  1206. if(attrs.editableForm && scope[attrs.editableForm] && scope[attrs.editableForm].$show) {
  1207. eForm = scope[attrs.editableForm];
  1208. } else {
  1209. eForm = ctrl[0];
  1210. }
  1211. /**
  1212. * Called when form is shown.
  1213. *
  1214. * @var {method|attribute} onshow
  1215. * @memberOf editable-form
  1216. */
  1217. if(attrs.onshow) {
  1218. eForm.$onshow = angular.bind(eForm, $parse(attrs.onshow), scope);
  1219. }
  1220. /**
  1221. * Called when form hides after both save or cancel.
  1222. *
  1223. * @var {method|attribute} onhide
  1224. * @memberOf editable-form
  1225. */
  1226. if(attrs.onhide) {
  1227. eForm.$onhide = angular.bind(eForm, $parse(attrs.onhide), scope);
  1228. }
  1229. /**
  1230. * Called when form is cancelled.
  1231. *
  1232. * @var {method|attribute} oncancel
  1233. * @memberOf editable-form
  1234. */
  1235. if(attrs.oncancel) {
  1236. eForm.$oncancel = angular.bind(eForm, $parse(attrs.oncancel), scope);
  1237. }
  1238. /**
  1239. * Whether form initially rendered in shown state.
  1240. *
  1241. * @var {bool|attribute} shown
  1242. * @memberOf editable-form
  1243. */
  1244. if(attrs.shown && $parse(attrs.shown)(scope)) {
  1245. eForm.$show();
  1246. }
  1247. /**
  1248. * Action when form losses focus. Values: `cancel|submit|ignore`.
  1249. * Default is `ignore`.
  1250. *
  1251. * @var {string|attribute} blur
  1252. * @memberOf editable-form
  1253. */
  1254. eForm._blur = attrs.blur || editableOptions.blurForm;
  1255. // onbeforesave, onaftersave
  1256. if(!attrs.ngSubmit && !attrs.submit) {
  1257. /**
  1258. * Called after all children `onbeforesave` callbacks but before saving form values
  1259. * to model.
  1260. * If at least one children callback returns `non-string` - it will not not be called.
  1261. * See [editable-form demo](#editable-form) for details.
  1262. *
  1263. * @var {method|attribute} onbeforesave
  1264. * @memberOf editable-form
  1265. *
  1266. */
  1267. if(attrs.onbeforesave) {
  1268. eForm.$onbeforesave = function() {
  1269. return $parse(attrs.onbeforesave)(scope, {$data: eForm.$data});
  1270. };
  1271. }
  1272. /**
  1273. * Called when form values are saved to model.
  1274. * See [editable-form demo](#editable-form) for details.
  1275. *
  1276. * @var {method|attribute} onaftersave
  1277. * @memberOf editable-form
  1278. *
  1279. */
  1280. if(attrs.onaftersave) {
  1281. eForm.$onaftersave = function() {
  1282. return $parse(attrs.onaftersave)(scope, {$data: eForm.$data});
  1283. };
  1284. }
  1285. elem.bind('submit', function(event) {
  1286. event.preventDefault();
  1287. scope.$apply(function() {
  1288. eForm.$submit();
  1289. });
  1290. });
  1291. }
  1292. // click - mark form as clicked to exclude in document click handler
  1293. elem.bind('click', function(e) {
  1294. // ignore right/middle button click
  1295. if (e.which && e.which !== 1) {
  1296. return;
  1297. }
  1298. if (eForm.$visible) {
  1299. eForm._clicked = true;
  1300. }
  1301. });
  1302. }
  1303. };
  1304. }
  1305. };
  1306. }]);
  1307. /**
  1308. * editablePromiseCollection
  1309. *
  1310. * Collect results of function calls. Shows waiting if there are promises.
  1311. * Finally, applies callbacks if:
  1312. * - onTrue(): all results are true and all promises resolved to true
  1313. * - onFalse(): at least one result is false or promise resolved to false
  1314. * - onString(): at least one result is string or promise rejected or promise resolved to string
  1315. */
  1316. angular.module('xeditable').factory('editablePromiseCollection', ['$q', function($q) {
  1317. function promiseCollection() {
  1318. return {
  1319. promises: [],
  1320. hasFalse: false,
  1321. hasString: false,
  1322. when: function(result, noPromise) {
  1323. if (result === false) {
  1324. this.hasFalse = true;
  1325. } else if (!noPromise && angular.isObject(result)) {
  1326. this.promises.push($q.when(result));
  1327. } else if (angular.isString(result)){
  1328. this.hasString = true;
  1329. } else { //result === true || result === undefined || result === null
  1330. return;
  1331. }
  1332. },
  1333. //callbacks: onTrue, onFalse, onString
  1334. then: function(callbacks) {
  1335. callbacks = callbacks || {};
  1336. var onTrue = callbacks.onTrue || angular.noop;
  1337. var onFalse = callbacks.onFalse || angular.noop;
  1338. var onString = callbacks.onString || angular.noop;
  1339. var onWait = callbacks.onWait || angular.noop;
  1340. var self = this;
  1341. if (this.promises.length) {
  1342. onWait(true);
  1343. $q.all(this.promises).then(
  1344. //all resolved
  1345. function(results) {
  1346. onWait(false);
  1347. //check all results via same `when` method (without checking promises)
  1348. angular.forEach(results, function(result) {
  1349. self.when(result, true);
  1350. });
  1351. applyCallback();
  1352. },
  1353. //some rejected
  1354. function(error) {
  1355. onWait(false);
  1356. onString();
  1357. }
  1358. );
  1359. } else {
  1360. applyCallback();
  1361. }
  1362. function applyCallback() {
  1363. if (!self.hasString && !self.hasFalse) {
  1364. onTrue();
  1365. } else if (!self.hasString && self.hasFalse) {
  1366. onFalse();
  1367. } else {
  1368. onString();
  1369. }
  1370. }
  1371. }
  1372. };
  1373. }
  1374. return promiseCollection;
  1375. }]);
  1376. /**
  1377. * editableUtils
  1378. */
  1379. angular.module('xeditable').factory('editableUtils', [function() {
  1380. return {
  1381. indexOf: function (array, obj) {
  1382. if (array.indexOf) return array.indexOf(obj);
  1383. for ( var i = 0; i < array.length; i++) {
  1384. if (obj === array[i]) return i;
  1385. }
  1386. return -1;
  1387. },
  1388. arrayRemove: function (array, value) {
  1389. var index = this.indexOf(array, value);
  1390. if (index >= 0) {
  1391. array.splice(index, 1);
  1392. }
  1393. return value;
  1394. },
  1395. // copy from https://github.com/angular/angular.js/blob/master/src/Angular.js
  1396. camelToDash: function(str) {
  1397. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1398. return str.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1399. return (pos ? '-' : '') + letter.toLowerCase();
  1400. });
  1401. },
  1402. dashToCamel: function(str) {
  1403. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  1404. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  1405. return str.
  1406. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  1407. return offset ? letter.toUpperCase() : letter;
  1408. }).
  1409. replace(MOZ_HACK_REGEXP, 'Moz$1');
  1410. }
  1411. };
  1412. }]);
  1413. /**
  1414. * editableNgOptionsParser
  1415. *
  1416. * see: https://github.com/angular/angular.js/blob/master/src/ng/directive/select.js#L131
  1417. */
  1418. angular.module('xeditable').factory('editableNgOptionsParser', [function() {
  1419. //0000111110000000000022220000000000000000000000333300000000000000444444444444444000000000555555555555555000000066666666666666600000000000000007777000000000000000000088888
  1420. var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+(.*?)(?:\s+track\s+by\s+(.*?))?$/;
  1421. function parser(optionsExp) {
  1422. var match;
  1423. if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) {
  1424. throw 'ng-options parse error';
  1425. }
  1426. var
  1427. displayFn = match[2] || match[1],
  1428. valueName = match[4] || match[6],
  1429. keyName = match[5],
  1430. groupByFn = match[3] || '',
  1431. valueFn = match[2] ? match[1] : valueName,
  1432. valuesFn = match[7],
  1433. track = match[8],
  1434. trackFn = track ? match[8] : null;
  1435. var ngRepeat;
  1436. if (keyName === undefined) { // array
  1437. ngRepeat = valueName + ' in ' + valuesFn;
  1438. if (track !== undefined) {
  1439. ngRepeat += ' track by '+trackFn;
  1440. }
  1441. } else { // object
  1442. ngRepeat = '('+keyName+', '+valueName+') in '+valuesFn;
  1443. }
  1444. // group not supported yet
  1445. return {
  1446. ngRepeat: ngRepeat,
  1447. locals: {
  1448. valueName: valueName,
  1449. keyName: keyName,
  1450. valueFn: valueFn,
  1451. displayFn: displayFn
  1452. }
  1453. };
  1454. }
  1455. return parser;
  1456. }]);
  1457. /**
  1458. * editableCombodate
  1459. *
  1460. * angular version of https://github.com/vitalets/combodate
  1461. */
  1462. angular.module('xeditable').factory('editableCombodate', [function() {
  1463. function Combodate(element, options) {
  1464. this.$element = angular.element(element);
  1465. if(this.$element[0].nodeName != 'INPUT') {
  1466. throw 'Combodate should be applied to INPUT element';
  1467. }
  1468. this.defaults = {
  1469. //in this format value stored in original input
  1470. format: 'YYYY-MM-DD HH:mm',
  1471. //in this format items in dropdowns are displayed
  1472. template: 'D / MMM / YYYY H : mm',
  1473. //initial value, can be `new Date()`
  1474. value: null,
  1475. minYear: 1970,
  1476. maxYear: 2015,
  1477. yearDescending: true,
  1478. minuteStep: 5,
  1479. secondStep: 1,
  1480. firstItem: 'empty', //'name', 'empty', 'none'
  1481. errorClass: null,
  1482. customClass: '',
  1483. roundTime: true, // whether to round minutes and seconds if step > 1
  1484. smartDays: true // whether days in combo depend on selected month: 31, 30, 28
  1485. };
  1486. this.options = angular.extend({}, this.defaults, options);
  1487. this.init();
  1488. }
  1489. Combodate.prototype = {
  1490. constructor: Combodate,
  1491. init: function () {
  1492. this.map = {
  1493. //key regexp moment.method
  1494. day: ['D', 'date'],
  1495. month: ['M', 'month'],
  1496. year: ['Y', 'year'],
  1497. hour: ['[Hh]', 'hours'],
  1498. minute: ['m', 'minutes'],
  1499. second: ['s', 'seconds'],
  1500. ampm: ['[Aa]', '']
  1501. };
  1502. this.$widget = angular.element('<span class="combodate"></span>').html(this.getTemplate());
  1503. this.initCombos();
  1504. if (this.options.smartDays) {
  1505. var combo = this;
  1506. this.$widget.find('select').bind('change', function(e) {
  1507. // update days count if month or year changes
  1508. if (angular.element(e.target).hasClass('month') || angular.element(e.target).hasClass('year')) {
  1509. combo.fillCombo('day');
  1510. }
  1511. });
  1512. }
  1513. this.$widget.find('select').css('width', 'auto');
  1514. // hide original input and insert widget
  1515. this.$element.css('display', 'none').after(this.$widget);
  1516. // set initial value
  1517. this.setValue(this.$element.val() || this.options.value);
  1518. },
  1519. /*
  1520. Replace tokens in template with <select> elements
  1521. */
  1522. getTemplate: function() {
  1523. var tpl = this.options.template;
  1524. var customClass = this.options.customClass;
  1525. //first pass
  1526. angular.forEach(this.map, function(v, k) {
  1527. v = v[0];
  1528. var r = new RegExp(v+'+');
  1529. var token = v.length > 1 ? v.substring(1, 2) : v;
  1530. tpl = tpl.replace(r, '{'+token+'}');
  1531. });
  1532. //replace spaces with &nbsp;
  1533. tpl = tpl.replace(/ /g, '&nbsp;');
  1534. //second pass
  1535. angular.forEach(this.map, function(v, k) {
  1536. v = v[0];
  1537. var token = v.length > 1 ? v.substring(1, 2) : v;
  1538. tpl = tpl.replace('{'+token+'}', '<select class="'+k+' '+customClass+'"></select>');
  1539. });
  1540. return tpl;
  1541. },
  1542. /*
  1543. Initialize combos that presents in template
  1544. */
  1545. initCombos: function() {
  1546. for (var k in this.map) {
  1547. var c = this.$widget[0].querySelectorAll('.'+k);
  1548. // set properties like this.$day, this.$month etc.
  1549. this['$'+k] = c.length ? angular.element(c) : null;
  1550. // fill with items
  1551. this.fillCombo(k);
  1552. }
  1553. },
  1554. /*
  1555. Fill combo with items
  1556. */
  1557. fillCombo: function(k) {
  1558. var $combo = this['$'+k];
  1559. if (!$combo) {
  1560. return;
  1561. }
  1562. // define method name to fill items, e.g `fillDays`
  1563. var f = 'fill' + k.charAt(0).toUpperCase() + k.slice(1);
  1564. var items = this[f]();
  1565. var value = $combo.val();
  1566. $combo.html('');
  1567. for(var i=0; i<items.length; i++) {
  1568. $combo.append('<option value="'+items[i][0]+'">'+items[i][1]+'</option>');
  1569. }
  1570. $combo.val(value);
  1571. },
  1572. /*
  1573. Initialize items of combos. Handles `firstItem` option
  1574. */
  1575. fillCommon: function(key) {
  1576. var values = [], relTime;
  1577. if(this.options.firstItem === 'name') {
  1578. //need both to support moment ver < 2 and >= 2
  1579. relTime = moment.relativeTime || moment.langData()._relativeTime;
  1580. var header = typeof relTime[key] === 'function' ? relTime[key](1, true, key, false) : relTime[key];
  1581. //take last entry (see momentjs lang files structure)
  1582. header = header.split(' ').reverse()[0];
  1583. values.push(['', header]);
  1584. } else if(this.options.firstItem === 'empty') {
  1585. values.push(['', '']);
  1586. }
  1587. return values;
  1588. },
  1589. /*
  1590. fill day
  1591. */
  1592. fillDay: function() {
  1593. var items = this.fillCommon('d'), name, i,
  1594. twoDigit = this.options.template.indexOf('DD') !== -1,
  1595. daysCount = 31;
  1596. // detect days count (depends on month and year)
  1597. // originally https://github.com/vitalets/combodate/pull/7
  1598. if (this.options.smartDays && this.$month && this.$year) {
  1599. var month = parseInt(this.$month.val(), 10);
  1600. var year = parseInt(this.$year.val(), 10);
  1601. if (!isNaN(month) && !isNaN(year)) {
  1602. daysCount = moment([year, month]).daysInMonth();
  1603. }
  1604. }
  1605. for (i = 1; i <= daysCount; i++) {
  1606. name = twoDigit ? this.leadZero(i) : i;
  1607. items.push([i, name]);
  1608. }
  1609. return items;
  1610. },
  1611. /*
  1612. fill month
  1613. */
  1614. fillMonth: function() {
  1615. var items = this.fillCommon('M'), name, i,
  1616. longNames = this.options.template.indexOf('MMMM') !== -1,
  1617. shortNames = this.options.template.indexOf('MMM') !== -1,
  1618. twoDigit = this.options.template.indexOf('MM') !== -1;
  1619. for(i=0; i<=11; i++) {
  1620. if(longNames) {
  1621. //see https://github.com/timrwood/momentjs.com/pull/36
  1622. name = moment().date(1).month(i).format('MMMM');
  1623. } else if(shortNames) {
  1624. name = moment().date(1).month(i).format('MMM');
  1625. } else if(twoDigit) {
  1626. name = this.leadZero(i+1);
  1627. } else {
  1628. name = i+1;
  1629. }
  1630. items.push([i, name]);
  1631. }
  1632. return items;
  1633. },
  1634. /*
  1635. fill year
  1636. */
  1637. fillYear: function() {
  1638. var items = [], name, i,
  1639. longNames = this.options.template.indexOf('YYYY') !== -1;
  1640. for(i=this.options.maxYear; i>=this.options.minYear; i--) {
  1641. name = longNames ? i : (i+'').substring(2);
  1642. items[this.options.yearDescending ? 'push' : 'unshift']([i, name]);
  1643. }
  1644. items = this.fillCommon('y').concat(items);
  1645. return items;
  1646. },
  1647. /*
  1648. fill hour
  1649. */
  1650. fillHour: function() {
  1651. var items = this.fillCommon('h'), name, i,
  1652. h12 = this.options.template.indexOf('h') !== -1,
  1653. h24 = this.options.template.indexOf('H') !== -1,
  1654. twoDigit = this.options.template.toLowerCase().indexOf('hh') !== -1,
  1655. min = h12 ? 1 : 0,
  1656. max = h12 ? 12 : 23;
  1657. for(i=min; i<=max; i++) {
  1658. name = twoDigit ? this.leadZero(i) : i;
  1659. items.push([i, name]);
  1660. }
  1661. return items;
  1662. },
  1663. /*
  1664. fill minute
  1665. */
  1666. fillMinute: function() {
  1667. var items = this.fillCommon('m'), name, i,
  1668. twoDigit = this.options.template.indexOf('mm') !== -1;
  1669. for(i=0; i<=59; i+= this.options.minuteStep) {
  1670. name = twoDigit ? this.leadZero(i) : i;
  1671. items.push([i, name]);
  1672. }
  1673. return items;
  1674. },
  1675. /*
  1676. fill second
  1677. */
  1678. fillSecond: function() {
  1679. var items = this.fillCommon('s'), name, i,
  1680. twoDigit = this.options.template.indexOf('ss') !== -1;
  1681. for(i=0; i<=59; i+= this.options.secondStep) {
  1682. name = twoDigit ? this.leadZero(i) : i;
  1683. items.push([i, name]);
  1684. }
  1685. return items;
  1686. },
  1687. /*
  1688. fill ampm
  1689. */
  1690. fillAmpm: function() {
  1691. var ampmL = this.options.template.indexOf('a') !== -1,
  1692. ampmU = this.options.template.indexOf('A') !== -1,
  1693. items = [
  1694. ['am', ampmL ? 'am' : 'AM'],
  1695. ['pm', ampmL ? 'pm' : 'PM']
  1696. ];
  1697. return items;
  1698. },
  1699. /*
  1700. Returns current date value from combos.
  1701. If format not specified - `options.format` used.
  1702. If format = `null` - Moment object returned.
  1703. */
  1704. getValue: function(format) {
  1705. var dt, values = {},
  1706. that = this,
  1707. notSelected = false;
  1708. //getting selected values
  1709. angular.forEach(this.map, function(v, k) {
  1710. if(k === 'ampm') {
  1711. return;
  1712. }
  1713. var def = k === 'day' ? 1 : 0;
  1714. values[k] = that['$'+k] ? parseInt(that['$'+k].val(), 10) : def;
  1715. if(isNaN(values[k])) {
  1716. notSelected = true;
  1717. return false;
  1718. }
  1719. });
  1720. //if at least one visible combo not selected - return empty string
  1721. if(notSelected) {
  1722. return '';
  1723. }
  1724. //convert hours 12h --> 24h
  1725. if(this.$ampm) {
  1726. //12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day)
  1727. if(values.hour === 12) {
  1728. values.hour = this.$ampm.val() === 'am' ? 0 : 12;
  1729. } else {
  1730. values.hour = this.$ampm.val() === 'am' ? values.hour : values.hour+12;
  1731. }
  1732. }
  1733. dt = moment([values.year, values.month, values.day, values.hour, values.minute, values.second]);
  1734. //highlight invalid date
  1735. this.highlight(dt);
  1736. format = format === undefined ? this.options.format : format;
  1737. if(format === null) {
  1738. return dt.isValid() ? dt : null;
  1739. } else {
  1740. return dt.isValid() ? dt.format(format) : '';
  1741. }
  1742. },
  1743. setValue: function(value) {
  1744. if(!value) {
  1745. return;
  1746. }
  1747. // parse in strict mode (third param `true`)
  1748. var dt = typeof value === 'string' ? moment(value, this.options.format, true) : moment(value),
  1749. that = this,
  1750. values = {};
  1751. //function to find nearest value in select options
  1752. function getNearest($select, value) {
  1753. var delta = {};
  1754. angular.forEach($select.children('option'), function(opt, i){
  1755. var optValue = angular.element(opt).attr('value');
  1756. if(optValue === '') return;
  1757. var distance = Math.abs(optValue - value);
  1758. if(typeof delta.distance === 'undefined' || distance < delta.distance) {
  1759. delta = {value: optValue, distance: distance};
  1760. }
  1761. });
  1762. return delta.value;
  1763. }
  1764. if(dt.isValid()) {
  1765. //read values from date object
  1766. angular.forEach(this.map, function(v, k) {
  1767. if(k === 'ampm') {
  1768. return;
  1769. }
  1770. values[k] = dt[v[1]]();
  1771. });
  1772. if(this.$ampm) {
  1773. //12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day)
  1774. if(values.hour >= 12) {
  1775. values.ampm = 'pm';
  1776. if(values.hour > 12) {
  1777. values.hour -= 12;
  1778. }
  1779. } else {
  1780. values.ampm = 'am';
  1781. if(values.hour === 0) {
  1782. values.hour = 12;
  1783. }
  1784. }
  1785. }
  1786. angular.forEach(values, function(v, k) {
  1787. //call val() for each existing combo, e.g. this.$hour.val()
  1788. if(that['$'+k]) {
  1789. if(k === 'minute' && that.options.minuteStep > 1 && that.options.roundTime) {
  1790. v = getNearest(that['$'+k], v);
  1791. }
  1792. if(k === 'second' && that.options.secondStep > 1 && that.options.roundTime) {
  1793. v = getNearest(that['$'+k], v);
  1794. }
  1795. that['$'+k].val(v);
  1796. }
  1797. });
  1798. // update days count
  1799. if (this.options.smartDays) {
  1800. this.fillCombo('day');
  1801. }
  1802. this.$element.val(dt.format(this.options.format)).triggerHandler('change');
  1803. }
  1804. },
  1805. /*
  1806. highlight combos if date is invalid
  1807. */
  1808. highlight: function(dt) {
  1809. if(!dt.isValid()) {
  1810. if(this.options.errorClass) {
  1811. this.$widget.addClass(this.options.errorClass);
  1812. } else {
  1813. //store original border color
  1814. if(!this.borderColor) {
  1815. this.borderColor = this.$widget.find('select').css('border-color');
  1816. }
  1817. this.$widget.find('select').css('border-color', 'red');
  1818. }
  1819. } else {
  1820. if(this.options.errorClass) {
  1821. this.$widget.removeClass(this.options.errorClass);
  1822. } else {
  1823. this.$widget.find('select').css('border-color', this.borderColor);
  1824. }
  1825. }
  1826. },
  1827. leadZero: function(v) {
  1828. return v <= 9 ? '0' + v : v;
  1829. },
  1830. destroy: function() {
  1831. this.$widget.remove();
  1832. this.$element.removeData('combodate').show();
  1833. }
  1834. };
  1835. return {
  1836. getInstance: function(element, options) {
  1837. return new Combodate(element, options);
  1838. }
  1839. };
  1840. }]);
  1841. /*
  1842. Editable icons:
  1843. - default
  1844. - font-awesome
  1845. */
  1846. angular.module('xeditable').factory('editableIcons', function() {
  1847. var icons = {
  1848. //Icon-set to use, defaults to bootstrap icons
  1849. default: {
  1850. 'bs2': {
  1851. ok: 'icon-ok icon-white',
  1852. cancel: 'icon-remove'
  1853. },
  1854. 'bs3': {
  1855. ok: 'glyphicon glyphicon-ok',
  1856. cancel: 'glyphicon glyphicon-remove'
  1857. }
  1858. },
  1859. external: {
  1860. 'font-awesome': {
  1861. ok: 'fa fa-check',
  1862. cancel: 'fa fa-times'
  1863. }
  1864. }
  1865. };
  1866. return icons;
  1867. });
  1868. /*
  1869. Editable themes:
  1870. - default
  1871. - bootstrap 2
  1872. - bootstrap 3
  1873. Note: in postrender() `this` is instance of editableController
  1874. */
  1875. angular.module('xeditable').factory('editableThemes', function() {
  1876. var themes = {
  1877. //default
  1878. 'default': {
  1879. formTpl: '<form class="editable-wrap"></form>',
  1880. noformTpl: '<span class="editable-wrap"></span>',
  1881. controlsTpl: '<span class="editable-controls"></span>',
  1882. inputTpl: '',
  1883. errorTpl: '<div class="editable-error" ng-show="$error" ng-bind="$error"></div>',
  1884. buttonsTpl: '<span class="editable-buttons"></span>',
  1885. submitTpl: '<button type="submit">save</button>',
  1886. cancelTpl: '<button type="button" ng-click="$form.$cancel()">cancel</button>'
  1887. },
  1888. //bs2
  1889. 'bs2': {
  1890. formTpl: '<form class="form-inline editable-wrap" role="form"></form>',
  1891. noformTpl: '<span class="editable-wrap"></span>',
  1892. controlsTpl: '<div class="editable-controls controls control-group" ng-class="{\'error\': $error}"></div>',
  1893. inputTpl: '',
  1894. errorTpl: '<div class="editable-error help-block" ng-show="$error" ng-bind="$error"></div>',
  1895. buttonsTpl: '<span class="editable-buttons"></span>',
  1896. submitTpl: '<button type="submit" class="btn btn-primary"><span></span></button>',
  1897. cancelTpl: '<button type="button" class="btn" ng-click="$form.$cancel()">'+
  1898. '<span></span>'+
  1899. '</button>'
  1900. },
  1901. //bs3
  1902. 'bs3': {
  1903. formTpl: '<form class="form-inline editable-wrap" role="form"></form>',
  1904. noformTpl: '<span class="editable-wrap"></span>',
  1905. controlsTpl: '<div class="editable-controls form-group" ng-class="{\'has-error\': $error}"></div>',
  1906. inputTpl: '',
  1907. errorTpl: '<div class="editable-error help-block" ng-show="$error" ng-bind="$error"></div>',
  1908. buttonsTpl: '<span class="editable-buttons"></span>',
  1909. submitTpl: '<button type="submit" class="btn btn-primary" ng-click="savedatas($parent.$data)"><span></span></button>',
  1910. cancelTpl: '<button type="button" class="btn btn-default" ng-click="$form.$cancel()">'+
  1911. '<span></span>'+
  1912. '</button>',
  1913. //bs3 specific prop to change buttons class: btn-sm, btn-lg
  1914. buttonsClass: '',
  1915. //bs3 specific prop to change standard inputs class: input-sm, input-lg
  1916. inputClass: '',
  1917. postrender: function() {
  1918. //apply `form-control` class to std inputs
  1919. switch(this.directiveName) {
  1920. case 'editableText':
  1921. case 'editableSelect':
  1922. case 'editableTextarea':
  1923. case 'editableEmail':
  1924. case 'editableTel':
  1925. case 'editableNumber':
  1926. case 'editableUrl':
  1927. case 'editableSearch':
  1928. case 'editableDate':
  1929. case 'editableDatetime':
  1930. case 'editableBsdate':
  1931. case 'editableTime':
  1932. case 'editableMonth':
  1933. case 'editableWeek':
  1934. this.inputEl.addClass('form-control');
  1935. if(this.theme.inputClass) {
  1936. // don`t apply `input-sm` and `input-lg` to select multiple
  1937. // should be fixed in bs itself!
  1938. if(this.inputEl.attr('multiple') &&
  1939. (this.theme.inputClass === 'input-sm' || this.theme.inputClass === 'input-lg')) {
  1940. break;
  1941. }
  1942. this.inputEl.addClass(this.theme.inputClass);
  1943. }
  1944. break;
  1945. case 'editableCheckbox':
  1946. this.editorEl.addClass('checkbox');
  1947. }
  1948. //apply buttonsClass (bs3 specific!)
  1949. if(this.buttonsEl && this.theme.buttonsClass) {
  1950. this.buttonsEl.find('button').addClass(this.theme.buttonsClass);
  1951. }
  1952. }
  1953. }
  1954. };
  1955. return themes;
  1956. });