xeditable.js 84 KB

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