ui-grid.edit.js 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  1. /*!
  2. * ui-grid - v4.4.6 - 2018-04-06
  3. * Copyright (c) 2018 ; License: MIT
  4. */
  5. (function () {
  6. 'use strict';
  7. /**
  8. * @ngdoc overview
  9. * @name ui.grid.edit
  10. * @description
  11. *
  12. * # ui.grid.edit
  13. *
  14. * <div class="alert alert-success" role="alert"><strong>Stable</strong> This feature is stable. There should no longer be breaking api changes without a deprecation warning.</div>
  15. *
  16. * This module provides cell editing capability to ui.grid. The goal was to emulate keying data in a spreadsheet via
  17. * a keyboard.
  18. * <br/>
  19. * <br/>
  20. * To really get the full spreadsheet-like data entry, the ui.grid.cellNav module should be used. This will allow the
  21. * user to key data and then tab, arrow, or enter to the cells beside or below.
  22. *
  23. * <div doc-module-components="ui.grid.edit"></div>
  24. */
  25. var module = angular.module('ui.grid.edit', ['ui.grid']);
  26. /**
  27. * @ngdoc object
  28. * @name ui.grid.edit.constant:uiGridEditConstants
  29. *
  30. * @description constants available in edit module
  31. */
  32. module.constant('uiGridEditConstants', {
  33. EDITABLE_CELL_TEMPLATE: /EDITABLE_CELL_TEMPLATE/g,
  34. //must be lowercase because template bulder converts to lower
  35. EDITABLE_CELL_DIRECTIVE: /editable_cell_directive/g,
  36. events: {
  37. BEGIN_CELL_EDIT: 'uiGridEventBeginCellEdit',
  38. END_CELL_EDIT: 'uiGridEventEndCellEdit',
  39. CANCEL_CELL_EDIT: 'uiGridEventCancelCellEdit'
  40. }
  41. });
  42. /**
  43. * @ngdoc service
  44. * @name ui.grid.edit.service:uiGridEditService
  45. *
  46. * @description Services for editing features
  47. */
  48. module.service('uiGridEditService', ['$q', 'uiGridConstants', 'gridUtil',
  49. function ($q, uiGridConstants, gridUtil) {
  50. var service = {
  51. initializeGrid: function (grid) {
  52. service.defaultGridOptions(grid.options);
  53. grid.registerColumnBuilder(service.editColumnBuilder);
  54. grid.edit = {};
  55. /**
  56. * @ngdoc object
  57. * @name ui.grid.edit.api:PublicApi
  58. *
  59. * @description Public Api for edit feature
  60. */
  61. var publicApi = {
  62. events: {
  63. edit: {
  64. /**
  65. * @ngdoc event
  66. * @name afterCellEdit
  67. * @eventOf ui.grid.edit.api:PublicApi
  68. * @description raised when cell editing is complete
  69. * <pre>
  70. * gridApi.edit.on.afterCellEdit(scope,function(rowEntity, colDef){})
  71. * </pre>
  72. * @param {object} rowEntity the options.data element that was edited
  73. * @param {object} colDef the column that was edited
  74. * @param {object} newValue new value
  75. * @param {object} oldValue old value
  76. */
  77. afterCellEdit: function (rowEntity, colDef, newValue, oldValue) {
  78. },
  79. /**
  80. * @ngdoc event
  81. * @name beginCellEdit
  82. * @eventOf ui.grid.edit.api:PublicApi
  83. * @description raised when cell editing starts on a cell
  84. * <pre>
  85. * gridApi.edit.on.beginCellEdit(scope,function(rowEntity, colDef){})
  86. * </pre>
  87. * @param {object} rowEntity the options.data element that was edited
  88. * @param {object} colDef the column that was edited
  89. * @param {object} triggerEvent the event that triggered the edit. Useful to prevent losing keystrokes on some
  90. * complex editors
  91. */
  92. beginCellEdit: function (rowEntity, colDef, triggerEvent) {
  93. },
  94. /**
  95. * @ngdoc event
  96. * @name cancelCellEdit
  97. * @eventOf ui.grid.edit.api:PublicApi
  98. * @description raised when cell editing is cancelled on a cell
  99. * <pre>
  100. * gridApi.edit.on.cancelCellEdit(scope,function(rowEntity, colDef){})
  101. * </pre>
  102. * @param {object} rowEntity the options.data element that was edited
  103. * @param {object} colDef the column that was edited
  104. */
  105. cancelCellEdit: function (rowEntity, colDef) {
  106. }
  107. }
  108. },
  109. methods: {
  110. edit: { }
  111. }
  112. };
  113. grid.api.registerEventsFromObject(publicApi.events);
  114. //grid.api.registerMethodsFromObject(publicApi.methods);
  115. },
  116. defaultGridOptions: function (gridOptions) {
  117. /**
  118. * @ngdoc object
  119. * @name ui.grid.edit.api:GridOptions
  120. *
  121. * @description Options for configuring the edit feature, these are available to be
  122. * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
  123. */
  124. /**
  125. * @ngdoc object
  126. * @name enableCellEdit
  127. * @propertyOf ui.grid.edit.api:GridOptions
  128. * @description If defined, sets the default value for the editable flag on each individual colDefs
  129. * if their individual enableCellEdit configuration is not defined. Defaults to undefined.
  130. */
  131. /**
  132. * @ngdoc object
  133. * @name cellEditableCondition
  134. * @propertyOf ui.grid.edit.api:GridOptions
  135. * @description If specified, either a value or function to be used by all columns before editing.
  136. * If false, then editing of cell is not allowed.
  137. * @example
  138. * <pre>
  139. * function($scope, triggerEvent){
  140. * //use $scope.row.entity, $scope.col.colDef and triggerEvent to determine if editing is allowed
  141. * return true;
  142. * }
  143. * </pre>
  144. */
  145. gridOptions.cellEditableCondition = gridOptions.cellEditableCondition === undefined ? true : gridOptions.cellEditableCondition;
  146. /**
  147. * @ngdoc object
  148. * @name editableCellTemplate
  149. * @propertyOf ui.grid.edit.api:GridOptions
  150. * @description If specified, cellTemplate to use as the editor for all columns.
  151. * <br/> defaults to 'ui-grid/cellTextEditor'
  152. */
  153. /**
  154. * @ngdoc object
  155. * @name enableCellEditOnFocus
  156. * @propertyOf ui.grid.edit.api:GridOptions
  157. * @description If true, then editor is invoked as soon as cell receives focus. Default false.
  158. * <br/>_requires cellNav feature and the edit feature to be enabled_
  159. */
  160. //enableCellEditOnFocus can only be used if cellnav module is used
  161. gridOptions.enableCellEditOnFocus = gridOptions.enableCellEditOnFocus === undefined ? false : gridOptions.enableCellEditOnFocus;
  162. },
  163. /**
  164. * @ngdoc service
  165. * @name editColumnBuilder
  166. * @methodOf ui.grid.edit.service:uiGridEditService
  167. * @description columnBuilder function that adds edit properties to grid column
  168. * @returns {promise} promise that will load any needed templates when resolved
  169. */
  170. editColumnBuilder: function (colDef, col, gridOptions) {
  171. var promises = [];
  172. /**
  173. * @ngdoc object
  174. * @name ui.grid.edit.api:ColumnDef
  175. *
  176. * @description Column Definition for edit feature, these are available to be
  177. * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
  178. */
  179. /**
  180. * @ngdoc object
  181. * @name enableCellEdit
  182. * @propertyOf ui.grid.edit.api:ColumnDef
  183. * @description enable editing on column
  184. */
  185. colDef.enableCellEdit = colDef.enableCellEdit === undefined ? (gridOptions.enableCellEdit === undefined ?
  186. (colDef.type !== 'object') : gridOptions.enableCellEdit) : colDef.enableCellEdit;
  187. /**
  188. * @ngdoc object
  189. * @name cellEditableCondition
  190. * @propertyOf ui.grid.edit.api:ColumnDef
  191. * @description If specified, either a value or function evaluated before editing cell. If falsy, then editing of cell is not allowed.
  192. * @example
  193. * <pre>
  194. * function($scope, triggerEvent){
  195. * //use $scope.row.entity, $scope.col.colDef and triggerEvent to determine if editing is allowed
  196. * return true;
  197. * }
  198. * </pre>
  199. */
  200. colDef.cellEditableCondition = colDef.cellEditableCondition === undefined ? gridOptions.cellEditableCondition : colDef.cellEditableCondition;
  201. /**
  202. * @ngdoc object
  203. * @name editableCellTemplate
  204. * @propertyOf ui.grid.edit.api:ColumnDef
  205. * @description cell template to be used when editing this column. Can be Url or text template
  206. * <br/>Defaults to gridOptions.editableCellTemplate
  207. */
  208. if (colDef.enableCellEdit) {
  209. colDef.editableCellTemplate = colDef.editableCellTemplate || gridOptions.editableCellTemplate || 'ui-grid/cellEditor';
  210. promises.push(gridUtil.getTemplate(colDef.editableCellTemplate)
  211. .then(
  212. function (template) {
  213. col.editableCellTemplate = template;
  214. },
  215. function (res) {
  216. // Todo handle response error here?
  217. throw new Error("Couldn't fetch/use colDef.editableCellTemplate '" + colDef.editableCellTemplate + "'");
  218. }));
  219. }
  220. /**
  221. * @ngdoc object
  222. * @name enableCellEditOnFocus
  223. * @propertyOf ui.grid.edit.api:ColumnDef
  224. * @requires ui.grid.cellNav
  225. * @description If true, then editor is invoked as soon as cell receives focus. Default false.
  226. * <br>_requires both the cellNav feature and the edit feature to be enabled_
  227. */
  228. //enableCellEditOnFocus can only be used if cellnav module is used
  229. colDef.enableCellEditOnFocus = colDef.enableCellEditOnFocus === undefined ? gridOptions.enableCellEditOnFocus : colDef.enableCellEditOnFocus;
  230. /**
  231. * @ngdoc string
  232. * @name editModelField
  233. * @propertyOf ui.grid.edit.api:ColumnDef
  234. * @description a bindable string value that is used when binding to edit controls instead of colDef.field
  235. * <br/> example: You have a complex property on and object like state:{abbrev:'MS',name:'Mississippi'}. The
  236. * grid should display state.name in the cell and sort/filter based on the state.name property but the editor
  237. * requires the full state object.
  238. * <br/>colDef.field = 'state.name'
  239. * <br/>colDef.editModelField = 'state'
  240. */
  241. //colDef.editModelField
  242. return $q.all(promises);
  243. },
  244. /**
  245. * @ngdoc service
  246. * @name isStartEditKey
  247. * @methodOf ui.grid.edit.service:uiGridEditService
  248. * @description Determines if a keypress should start editing. Decorate this service to override with your
  249. * own key events. See service decorator in angular docs.
  250. * @param {Event} evt keydown event
  251. * @returns {boolean} true if an edit should start
  252. */
  253. isStartEditKey: function (evt) {
  254. if (evt.metaKey ||
  255. evt.keyCode === uiGridConstants.keymap.ESC ||
  256. evt.keyCode === uiGridConstants.keymap.SHIFT ||
  257. evt.keyCode === uiGridConstants.keymap.CTRL ||
  258. evt.keyCode === uiGridConstants.keymap.ALT ||
  259. evt.keyCode === uiGridConstants.keymap.WIN ||
  260. evt.keyCode === uiGridConstants.keymap.CAPSLOCK ||
  261. evt.keyCode === uiGridConstants.keymap.LEFT ||
  262. (evt.keyCode === uiGridConstants.keymap.TAB && evt.shiftKey) ||
  263. evt.keyCode === uiGridConstants.keymap.RIGHT ||
  264. evt.keyCode === uiGridConstants.keymap.TAB ||
  265. evt.keyCode === uiGridConstants.keymap.UP ||
  266. (evt.keyCode === uiGridConstants.keymap.ENTER && evt.shiftKey) ||
  267. evt.keyCode === uiGridConstants.keymap.DOWN ||
  268. evt.keyCode === uiGridConstants.keymap.ENTER) {
  269. return false;
  270. }
  271. return true;
  272. }
  273. };
  274. return service;
  275. }]);
  276. /**
  277. * @ngdoc directive
  278. * @name ui.grid.edit.directive:uiGridEdit
  279. * @element div
  280. * @restrict A
  281. *
  282. * @description Adds editing features to the ui-grid directive.
  283. *
  284. * @example
  285. <example module="app">
  286. <file name="app.js">
  287. var app = angular.module('app', ['ui.grid', 'ui.grid.edit']);
  288. app.controller('MainCtrl', ['$scope', function ($scope) {
  289. $scope.data = [
  290. { name: 'Bob', title: 'CEO' },
  291. { name: 'Frank', title: 'Lowly Developer' }
  292. ];
  293. $scope.columnDefs = [
  294. {name: 'name', enableCellEdit: true},
  295. {name: 'title', enableCellEdit: true}
  296. ];
  297. }]);
  298. </file>
  299. <file name="index.html">
  300. <div ng-controller="MainCtrl">
  301. <div ui-grid="{ data: data, columnDefs: columnDefs }" ui-grid-edit></div>
  302. </div>
  303. </file>
  304. </example>
  305. */
  306. module.directive('uiGridEdit', ['gridUtil', 'uiGridEditService', function (gridUtil, uiGridEditService) {
  307. return {
  308. replace: true,
  309. priority: 0,
  310. require: '^uiGrid',
  311. scope: false,
  312. compile: function () {
  313. return {
  314. pre: function ($scope, $elm, $attrs, uiGridCtrl) {
  315. uiGridEditService.initializeGrid(uiGridCtrl.grid);
  316. },
  317. post: function ($scope, $elm, $attrs, uiGridCtrl) {
  318. }
  319. };
  320. }
  321. };
  322. }]);
  323. /**
  324. * @ngdoc directive
  325. * @name ui.grid.edit.directive:uiGridRenderContainer
  326. * @element div
  327. * @restrict A
  328. *
  329. * @description Adds keydown listeners to renderContainer element so we can capture when to begin edits
  330. *
  331. */
  332. module.directive('uiGridViewport', [ 'uiGridEditConstants',
  333. function ( uiGridEditConstants) {
  334. return {
  335. replace: true,
  336. priority: -99998, //run before cellNav
  337. require: ['^uiGrid', '^uiGridRenderContainer'],
  338. scope: false,
  339. compile: function () {
  340. return {
  341. post: function ($scope, $elm, $attrs, controllers) {
  342. var uiGridCtrl = controllers[0];
  343. // Skip attaching if edit and cellNav is not enabled
  344. if (!uiGridCtrl.grid.api.edit || !uiGridCtrl.grid.api.cellNav) { return; }
  345. var containerId = controllers[1].containerId;
  346. //no need to process for other containers
  347. if (containerId !== 'body') {
  348. return;
  349. }
  350. //refocus on the grid
  351. $scope.$on(uiGridEditConstants.events.CANCEL_CELL_EDIT, function () {
  352. uiGridCtrl.focus();
  353. });
  354. $scope.$on(uiGridEditConstants.events.END_CELL_EDIT, function () {
  355. uiGridCtrl.focus();
  356. });
  357. }
  358. };
  359. }
  360. };
  361. }]);
  362. /**
  363. * @ngdoc directive
  364. * @name ui.grid.edit.directive:uiGridCell
  365. * @element div
  366. * @restrict A
  367. *
  368. * @description Stacks on top of ui.grid.uiGridCell to provide in-line editing capabilities to the cell
  369. * Editing Actions.
  370. *
  371. * Binds edit start events to the uiGridCell element. When the events fire, the gridCell element is appended
  372. * with the columnDef.editableCellTemplate element ('cellEditor.html' by default).
  373. *
  374. * The editableCellTemplate should respond to uiGridEditConstants.events.BEGIN\_CELL\_EDIT angular event
  375. * and do the initial steps needed to edit the cell (setfocus on input element, etc).
  376. *
  377. * When the editableCellTemplate recognizes that the editing is ended (blur event, Enter key, etc.)
  378. * it should emit the uiGridEditConstants.events.END\_CELL\_EDIT event.
  379. *
  380. * If editableCellTemplate recognizes that the editing has been cancelled (esc key)
  381. * it should emit the uiGridEditConstants.events.CANCEL\_CELL\_EDIT event. The original value
  382. * will be set back on the model by the uiGridCell directive.
  383. *
  384. * Events that invoke editing:
  385. * - dblclick
  386. * - F2 keydown (when using cell selection)
  387. *
  388. * Events that end editing:
  389. * - Dependent on the specific editableCellTemplate
  390. * - Standards should be blur and enter keydown
  391. *
  392. * Events that cancel editing:
  393. * - Dependent on the specific editableCellTemplate
  394. * - Standards should be Esc keydown
  395. *
  396. * Grid Events that end editing:
  397. * - uiGridConstants.events.GRID_SCROLL
  398. *
  399. */
  400. /**
  401. * @ngdoc object
  402. * @name ui.grid.edit.api:GridRow
  403. *
  404. * @description GridRow options for edit feature, these are available to be
  405. * set internally only, by other features
  406. */
  407. /**
  408. * @ngdoc object
  409. * @name enableCellEdit
  410. * @propertyOf ui.grid.edit.api:GridRow
  411. * @description enable editing on row, grouping for example might disable editing on group header rows
  412. */
  413. module.directive('uiGridCell',
  414. ['$compile', '$injector', '$timeout', 'uiGridConstants', 'uiGridEditConstants', 'gridUtil', '$parse', 'uiGridEditService', '$rootScope', '$q',
  415. function ($compile, $injector, $timeout, uiGridConstants, uiGridEditConstants, gridUtil, $parse, uiGridEditService, $rootScope, $q) {
  416. var touchstartTimeout = 500;
  417. if ($injector.has('uiGridCellNavService')) {
  418. var uiGridCellNavService = $injector.get('uiGridCellNavService');
  419. }
  420. return {
  421. priority: -100, // run after default uiGridCell directive
  422. restrict: 'A',
  423. scope: false,
  424. require: '?^uiGrid',
  425. link: function ($scope, $elm, $attrs, uiGridCtrl) {
  426. var html;
  427. var origCellValue;
  428. var inEdit = false;
  429. var cellModel;
  430. var cancelTouchstartTimeout;
  431. var editCellScope;
  432. if (!$scope.col.colDef.enableCellEdit) {
  433. return;
  434. }
  435. var cellNavNavigateDereg = function() {};
  436. var viewPortKeyDownDereg = function() {};
  437. var setEditable = function() {
  438. if ($scope.col.colDef.enableCellEdit && $scope.row.enableCellEdit !== false) {
  439. if (!$scope.beginEditEventsWired) { //prevent multiple attachments
  440. registerBeginEditEvents();
  441. }
  442. } else {
  443. if ($scope.beginEditEventsWired) {
  444. cancelBeginEditEvents();
  445. }
  446. }
  447. };
  448. setEditable();
  449. var rowWatchDereg = $scope.$watch('row', function (n, o) {
  450. if (n !== o) {
  451. setEditable();
  452. }
  453. });
  454. $scope.$on('$destroy', function destroyEvents() {
  455. rowWatchDereg();
  456. // unbind all jquery events in order to avoid memory leaks
  457. $elm.off();
  458. });
  459. function registerBeginEditEvents() {
  460. $elm.on('dblclick', beginEdit);
  461. // Add touchstart handling. If the users starts a touch and it doesn't end after X milliseconds, then start the edit
  462. $elm.on('touchstart', touchStart);
  463. if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
  464. viewPortKeyDownDereg = uiGridCtrl.grid.api.cellNav.on.viewPortKeyDown($scope, function (evt, rowCol) {
  465. if (rowCol === null) {
  466. return;
  467. }
  468. if (rowCol.row === $scope.row && rowCol.col === $scope.col && !$scope.col.colDef.enableCellEditOnFocus) {
  469. //important to do this before scrollToIfNecessary
  470. beginEditKeyDown(evt);
  471. }
  472. });
  473. cellNavNavigateDereg = uiGridCtrl.grid.api.cellNav.on.navigate($scope, function (newRowCol, oldRowCol, evt) {
  474. if ($scope.col.colDef.enableCellEditOnFocus) {
  475. // Don't begin edit if the cell hasn't changed
  476. if (newRowCol.row === $scope.row && newRowCol.col === $scope.col &&
  477. (!evt || (evt && (evt.type === 'click' || evt.type === 'keydown')))) {
  478. $timeout(function() {
  479. beginEdit(evt);
  480. });
  481. }
  482. }
  483. });
  484. }
  485. $scope.beginEditEventsWired = true;
  486. }
  487. function touchStart(event) {
  488. // jQuery masks events
  489. if (typeof(event.originalEvent) !== 'undefined' && event.originalEvent !== undefined) {
  490. event = event.originalEvent;
  491. }
  492. // Bind touchend handler
  493. $elm.on('touchend', touchEnd);
  494. // Start a timeout
  495. cancelTouchstartTimeout = $timeout(function() { }, touchstartTimeout);
  496. // Timeout's done! Start the edit
  497. cancelTouchstartTimeout.then(function () {
  498. // Use setTimeout to start the edit because beginEdit expects to be outside of $digest
  499. setTimeout(beginEdit, 0);
  500. // Undbind the touchend handler, we don't need it anymore
  501. $elm.off('touchend', touchEnd);
  502. });
  503. }
  504. // Cancel any touchstart timeout
  505. function touchEnd(event) {
  506. $timeout.cancel(cancelTouchstartTimeout);
  507. $elm.off('touchend', touchEnd);
  508. }
  509. function cancelBeginEditEvents() {
  510. $elm.off('dblclick', beginEdit);
  511. $elm.off('keydown', beginEditKeyDown);
  512. $elm.off('touchstart', touchStart);
  513. cellNavNavigateDereg();
  514. viewPortKeyDownDereg();
  515. $scope.beginEditEventsWired = false;
  516. }
  517. function beginEditKeyDown(evt) {
  518. if (uiGridEditService.isStartEditKey(evt)) {
  519. beginEdit(evt);
  520. }
  521. }
  522. function shouldEdit(col, row, triggerEvent) {
  523. return !row.isSaving &&
  524. ( angular.isFunction(col.colDef.cellEditableCondition) ?
  525. col.colDef.cellEditableCondition($scope, triggerEvent) :
  526. col.colDef.cellEditableCondition );
  527. }
  528. function beginEdit(triggerEvent) {
  529. //we need to scroll the cell into focus before invoking the editor
  530. $scope.grid.api.core.scrollToIfNecessary($scope.row, $scope.col)
  531. .then(function () {
  532. beginEditAfterScroll(triggerEvent);
  533. });
  534. }
  535. /**
  536. * @ngdoc property
  537. * @name editDropdownOptionsArray
  538. * @propertyOf ui.grid.edit.api:ColumnDef
  539. * @description an array of values in the format
  540. * [ {id: xxx, value: xxx} ], which is populated
  541. * into the edit dropdown
  542. *
  543. */
  544. /**
  545. * @ngdoc property
  546. * @name editDropdownIdLabel
  547. * @propertyOf ui.grid.edit.api:ColumnDef
  548. * @description the label for the "id" field
  549. * in the editDropdownOptionsArray. Defaults
  550. * to 'id'
  551. * @example
  552. * <pre>
  553. * $scope.gridOptions = {
  554. * columnDefs: [
  555. * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor',
  556. * editDropdownOptionsArray: [{code: 1, status: 'active'}, {code: 2, status: 'inactive'}],
  557. * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' }
  558. * ],
  559. * </pre>
  560. *
  561. */
  562. /**
  563. * @ngdoc property
  564. * @name editDropdownRowEntityOptionsArrayPath
  565. * @propertyOf ui.grid.edit.api:ColumnDef
  566. * @description a path to a property on row.entity containing an
  567. * array of values in the format
  568. * [ {id: xxx, value: xxx} ], which will be used to populate
  569. * the edit dropdown. This can be used when the dropdown values are dependent on
  570. * the backing row entity.
  571. * If this property is set then editDropdownOptionsArray will be ignored.
  572. * @example
  573. * <pre>
  574. * $scope.gridOptions = {
  575. * columnDefs: [
  576. * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor',
  577. * editDropdownRowEntityOptionsArrayPath: 'foo.bars[0].baz',
  578. * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' }
  579. * ],
  580. * </pre>
  581. *
  582. */
  583. /**
  584. * @ngdoc service
  585. * @name editDropdownOptionsFunction
  586. * @methodOf ui.grid.edit.api:ColumnDef
  587. * @description a function returning an array of values in the format
  588. * [ {id: xxx, value: xxx} ], which will be used to populate
  589. * the edit dropdown. This can be used when the dropdown values are dependent on
  590. * the backing row entity with some kind of algorithm.
  591. * If this property is set then both editDropdownOptionsArray and
  592. * editDropdownRowEntityOptionsArrayPath will be ignored.
  593. * @param {object} rowEntity the options.data element that the returned array refers to
  594. * @param {object} colDef the column that implements this dropdown
  595. * @returns {object} an array of values in the format
  596. * [ {id: xxx, value: xxx} ] used to populate the edit dropdown
  597. * @example
  598. * <pre>
  599. * $scope.gridOptions = {
  600. * columnDefs: [
  601. * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor',
  602. * editDropdownOptionsFunction: function(rowEntity, colDef) {
  603. * if (rowEntity.foo === 'bar') {
  604. * return [{id: 'bar1', value: 'BAR 1'},
  605. * {id: 'bar2', value: 'BAR 2'},
  606. * {id: 'bar3', value: 'BAR 3'}];
  607. * } else {
  608. * return [{id: 'foo1', value: 'FOO 1'},
  609. * {id: 'foo2', value: 'FOO 2'}];
  610. * }
  611. * },
  612. * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' }
  613. * ],
  614. * </pre>
  615. *
  616. */
  617. /**
  618. * @ngdoc property
  619. * @name editDropdownValueLabel
  620. * @propertyOf ui.grid.edit.api:ColumnDef
  621. * @description the label for the "value" field
  622. * in the editDropdownOptionsArray. Defaults
  623. * to 'value'
  624. * @example
  625. * <pre>
  626. * $scope.gridOptions = {
  627. * columnDefs: [
  628. * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor',
  629. * editDropdownOptionsArray: [{code: 1, status: 'active'}, {code: 2, status: 'inactive'}],
  630. * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' }
  631. * ],
  632. * </pre>
  633. *
  634. */
  635. /**
  636. * @ngdoc property
  637. * @name editDropdownFilter
  638. * @propertyOf ui.grid.edit.api:ColumnDef
  639. * @description A filter that you would like to apply to the values in the options list
  640. * of the dropdown. For example if you were using angular-translate you might set this
  641. * to `'translate'`
  642. * @example
  643. * <pre>
  644. * $scope.gridOptions = {
  645. * columnDefs: [
  646. * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor',
  647. * editDropdownOptionsArray: [{code: 1, status: 'active'}, {code: 2, status: 'inactive'}],
  648. * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status', editDropdownFilter: 'translate' }
  649. * ],
  650. * </pre>
  651. *
  652. */
  653. function beginEditAfterScroll(triggerEvent) {
  654. // If we are already editing, then just skip this so we don't try editing twice...
  655. if (inEdit) {
  656. return;
  657. }
  658. if (!shouldEdit($scope.col, $scope.row, triggerEvent)) {
  659. return;
  660. }
  661. var modelField = $scope.row.getQualifiedColField($scope.col);
  662. if ($scope.col.colDef.editModelField) {
  663. modelField = gridUtil.preEval('row.entity.' + $scope.col.colDef.editModelField);
  664. }
  665. cellModel = $parse(modelField);
  666. //get original value from the cell
  667. origCellValue = cellModel($scope);
  668. html = $scope.col.editableCellTemplate;
  669. html = html.replace(uiGridConstants.MODEL_COL_FIELD, modelField);
  670. html = html.replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)');
  671. var optionFilter = $scope.col.colDef.editDropdownFilter ? '|' + $scope.col.colDef.editDropdownFilter : '';
  672. html = html.replace(uiGridConstants.CUSTOM_FILTERS, optionFilter);
  673. var inputType = 'text';
  674. switch ($scope.col.colDef.type){
  675. case 'boolean':
  676. inputType = 'checkbox';
  677. break;
  678. case 'number':
  679. inputType = 'number';
  680. break;
  681. case 'date':
  682. inputType = 'date';
  683. break;
  684. }
  685. html = html.replace('INPUT_TYPE', inputType);
  686. // In order to fill dropdown options we use:
  687. // - A function/promise or
  688. // - An array inside of row entity if no function exists or
  689. // - A single array for the whole column if none of the previous exists.
  690. var editDropdownOptionsFunction = $scope.col.colDef.editDropdownOptionsFunction;
  691. if (editDropdownOptionsFunction) {
  692. $q.when(editDropdownOptionsFunction($scope.row.entity, $scope.col.colDef))
  693. .then(function(result) {
  694. $scope.editDropdownOptionsArray = result;
  695. });
  696. } else {
  697. var editDropdownRowEntityOptionsArrayPath = $scope.col.colDef.editDropdownRowEntityOptionsArrayPath;
  698. if (editDropdownRowEntityOptionsArrayPath) {
  699. $scope.editDropdownOptionsArray = resolveObjectFromPath($scope.row.entity, editDropdownRowEntityOptionsArrayPath);
  700. }
  701. else {
  702. $scope.editDropdownOptionsArray = $scope.col.colDef.editDropdownOptionsArray;
  703. }
  704. }
  705. $scope.editDropdownIdLabel = $scope.col.colDef.editDropdownIdLabel ? $scope.col.colDef.editDropdownIdLabel : 'id';
  706. $scope.editDropdownValueLabel = $scope.col.colDef.editDropdownValueLabel ? $scope.col.colDef.editDropdownValueLabel : 'value';
  707. var cellElement;
  708. var createEditor = function(){
  709. inEdit = true;
  710. cancelBeginEditEvents();
  711. var cellElement = angular.element(html);
  712. $elm.append(cellElement);
  713. editCellScope = $scope.$new();
  714. $compile(cellElement)(editCellScope);
  715. var gridCellContentsEl = angular.element($elm.children()[0]);
  716. gridCellContentsEl.addClass('ui-grid-cell-contents-hidden');
  717. };
  718. if (!$rootScope.$$phase) {
  719. $scope.$apply(createEditor);
  720. } else {
  721. createEditor();
  722. }
  723. //stop editing when grid is scrolled
  724. var deregOnGridScroll = $scope.col.grid.api.core.on.scrollBegin($scope, function () {
  725. if ($scope.grid.disableScrolling) {
  726. return;
  727. }
  728. endEdit();
  729. $scope.grid.api.edit.raise.afterCellEdit($scope.row.entity, $scope.col.colDef, cellModel($scope), origCellValue);
  730. deregOnGridScroll();
  731. deregOnEndCellEdit();
  732. deregOnCancelCellEdit();
  733. });
  734. //end editing
  735. var deregOnEndCellEdit = $scope.$on(uiGridEditConstants.events.END_CELL_EDIT, function () {
  736. endEdit();
  737. $scope.grid.api.edit.raise.afterCellEdit($scope.row.entity, $scope.col.colDef, cellModel($scope), origCellValue);
  738. deregOnEndCellEdit();
  739. deregOnGridScroll();
  740. deregOnCancelCellEdit();
  741. });
  742. //cancel editing
  743. var deregOnCancelCellEdit = $scope.$on(uiGridEditConstants.events.CANCEL_CELL_EDIT, function () {
  744. cancelEdit();
  745. deregOnCancelCellEdit();
  746. deregOnGridScroll();
  747. deregOnEndCellEdit();
  748. });
  749. $scope.$broadcast(uiGridEditConstants.events.BEGIN_CELL_EDIT, triggerEvent);
  750. $timeout(function () {
  751. // execute in a timeout to give any complex editor templates a cycle to completely render
  752. $scope.grid.api.edit.raise.beginCellEdit($scope.row.entity, $scope.col.colDef, triggerEvent);
  753. });
  754. }
  755. function endEdit() {
  756. $scope.grid.disableScrolling = false;
  757. if (!inEdit) {
  758. return;
  759. }
  760. //sometimes the events can't keep up with the keyboard and grid focus is lost, so always focus
  761. //back to grid here. The focus call needs to be before the $destroy and removal of the control,
  762. //otherwise ng-model-options of UpdateOn: 'blur' will not work.
  763. if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
  764. uiGridCtrl.focus();
  765. }
  766. var gridCellContentsEl = angular.element($elm.children()[0]);
  767. //remove edit element
  768. editCellScope.$destroy();
  769. var children = $elm.children();
  770. for (var i = 1; i < children.length; i++) {
  771. angular.element(children[i]).remove();
  772. }
  773. gridCellContentsEl.removeClass('ui-grid-cell-contents-hidden');
  774. inEdit = false;
  775. registerBeginEditEvents();
  776. $scope.grid.api.core.notifyDataChange( uiGridConstants.dataChange.EDIT );
  777. }
  778. function cancelEdit() {
  779. $scope.grid.disableScrolling = false;
  780. if (!inEdit) {
  781. return;
  782. }
  783. cellModel.assign($scope, origCellValue);
  784. $scope.$apply();
  785. $scope.grid.api.edit.raise.cancelCellEdit($scope.row.entity, $scope.col.colDef);
  786. endEdit();
  787. }
  788. // resolves a string path against the given object
  789. // shamelessly borrowed from
  790. // http://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key
  791. function resolveObjectFromPath(object, path) {
  792. path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
  793. path = path.replace(/^\./, ''); // strip a leading dot
  794. var a = path.split('.');
  795. while (a.length) {
  796. var n = a.shift();
  797. if (n in object) {
  798. object = object[n];
  799. } else {
  800. return;
  801. }
  802. }
  803. return object;
  804. }
  805. }
  806. };
  807. }]);
  808. /**
  809. * @ngdoc directive
  810. * @name ui.grid.edit.directive:uiGridEditor
  811. * @element div
  812. * @restrict A
  813. *
  814. * @description input editor directive for editable fields.
  815. * Provides EndEdit and CancelEdit events
  816. *
  817. * Events that end editing:
  818. * blur and enter keydown
  819. *
  820. * Events that cancel editing:
  821. * - Esc keydown
  822. *
  823. */
  824. module.directive('uiGridEditor',
  825. ['gridUtil', 'uiGridConstants', 'uiGridEditConstants','$timeout', 'uiGridEditService',
  826. function (gridUtil, uiGridConstants, uiGridEditConstants, $timeout, uiGridEditService) {
  827. return {
  828. scope: true,
  829. require: ['?^uiGrid', '?^uiGridRenderContainer', 'ngModel'],
  830. compile: function () {
  831. return {
  832. pre: function ($scope, $elm, $attrs) {
  833. },
  834. post: function ($scope, $elm, $attrs, controllers) {
  835. var uiGridCtrl, renderContainerCtrl, ngModel;
  836. if (controllers[0]) { uiGridCtrl = controllers[0]; }
  837. if (controllers[1]) { renderContainerCtrl = controllers[1]; }
  838. if (controllers[2]) { ngModel = controllers[2]; }
  839. //set focus at start of edit
  840. $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function (evt,triggerEvent) {
  841. // must be in a timeout since it requires a new digest cycle
  842. $timeout(function () {
  843. $elm[0].focus();
  844. //only select text if it is not being replaced below in the cellNav viewPortKeyPress
  845. if ($elm[0].select && ($scope.col.colDef.enableCellEditOnFocus || !(uiGridCtrl && uiGridCtrl.grid.api.cellNav))) {
  846. $elm[0].select();
  847. }
  848. else {
  849. //some browsers (Chrome) stupidly, imo, support the w3 standard that number, email, ...
  850. //fields should not allow setSelectionRange. We ignore the error for those browsers
  851. //https://www.w3.org/Bugs/Public/show_bug.cgi?id=24796
  852. try {
  853. $elm[0].setSelectionRange($elm[0].value.length, $elm[0].value.length);
  854. }
  855. catch (ex) {
  856. //ignore
  857. }
  858. }
  859. });
  860. //set the keystroke that started the edit event
  861. //we must do this because the BeginEdit is done in a different event loop than the intitial
  862. //keydown event
  863. //fire this event for the keypress that is received
  864. if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
  865. var viewPortKeyDownUnregister = uiGridCtrl.grid.api.cellNav.on.viewPortKeyPress($scope, function (evt, rowCol) {
  866. if (uiGridEditService.isStartEditKey(evt)) {
  867. var code = typeof evt.which === 'number' ? evt.which : evt.keyCode;
  868. if (code > 0) {
  869. ngModel.$setViewValue(String.fromCharCode(code), evt);
  870. ngModel.$render();
  871. }
  872. }
  873. viewPortKeyDownUnregister();
  874. });
  875. }
  876. // macOS will blur the checkbox when clicked in Safari and Firefox,
  877. // to get around this, we disable the blur handler on mousedown,
  878. // and then focus the checkbox and re-enable the blur handler after $timeout
  879. $elm.on('mousedown', function(evt) {
  880. if ($elm[0].type === 'checkbox') {
  881. $elm.off('blur', $scope.stopEdit);
  882. $timeout(function() {
  883. $elm[0].focus();
  884. $elm.on('blur', $scope.stopEdit);
  885. });
  886. }
  887. });
  888. $elm.on('blur', $scope.stopEdit);
  889. });
  890. $scope.deepEdit = false;
  891. $scope.stopEdit = function (evt) {
  892. if ($scope.inputForm && !$scope.inputForm.$valid) {
  893. evt.stopPropagation();
  894. $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT);
  895. }
  896. else {
  897. $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
  898. }
  899. $scope.deepEdit = false;
  900. };
  901. $elm.on('click', function (evt) {
  902. if ($elm[0].type !== 'checkbox') {
  903. $scope.deepEdit = true;
  904. $scope.$applyAsync(function () {
  905. $scope.grid.disableScrolling = true;
  906. });
  907. }
  908. });
  909. $elm.on('keydown', function (evt) {
  910. switch (evt.keyCode) {
  911. case uiGridConstants.keymap.ESC:
  912. evt.stopPropagation();
  913. $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT);
  914. break;
  915. }
  916. if ($scope.deepEdit &&
  917. (evt.keyCode === uiGridConstants.keymap.LEFT ||
  918. evt.keyCode === uiGridConstants.keymap.RIGHT ||
  919. evt.keyCode === uiGridConstants.keymap.UP ||
  920. evt.keyCode === uiGridConstants.keymap.DOWN)) {
  921. evt.stopPropagation();
  922. }
  923. // Pass the keydown event off to the cellNav service, if it exists
  924. else if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
  925. evt.uiGridTargetRenderContainerId = renderContainerCtrl.containerId;
  926. if (uiGridCtrl.cellNav.handleKeyDown(evt) !== null) {
  927. $scope.stopEdit(evt);
  928. }
  929. }
  930. else {
  931. //handle enter and tab for editing not using cellNav
  932. switch (evt.keyCode) {
  933. case uiGridConstants.keymap.ENTER: // Enter (Leave Field)
  934. case uiGridConstants.keymap.TAB:
  935. evt.stopPropagation();
  936. evt.preventDefault();
  937. $scope.stopEdit(evt);
  938. break;
  939. }
  940. }
  941. return true;
  942. });
  943. $scope.$on('$destroy', function unbindEvents() {
  944. // unbind all jquery events in order to avoid memory leaks
  945. $elm.off();
  946. });
  947. }
  948. };
  949. }
  950. };
  951. }]);
  952. /**
  953. * @ngdoc directive
  954. * @name ui.grid.edit.directive:input
  955. * @element input
  956. * @restrict E
  957. *
  958. * @description directive to provide binding between input[date] value and ng-model for angular 1.2
  959. * It is similar to input[date] directive of angular 1.3
  960. *
  961. * Supported date format for input is 'yyyy-MM-dd'
  962. * The directive will set the $valid property of input element and the enclosing form to false if
  963. * model is invalid date or value of input is entered wrong.
  964. *
  965. */
  966. module.directive('uiGridEditor', ['$filter', function ($filter) {
  967. function parseDateString(dateString) {
  968. if (typeof(dateString) === 'undefined' || dateString === '') {
  969. return null;
  970. }
  971. var parts = dateString.split('-');
  972. if (parts.length !== 3) {
  973. return null;
  974. }
  975. var year = parseInt(parts[0], 10);
  976. var month = parseInt(parts[1], 10);
  977. var day = parseInt(parts[2], 10);
  978. if (month < 1 || year < 1 || day < 1) {
  979. return null;
  980. }
  981. return new Date(year, (month - 1), day);
  982. }
  983. return {
  984. priority: -100, // run after default uiGridEditor directive
  985. require: '?ngModel',
  986. link: function (scope, element, attrs, ngModel) {
  987. if (angular.version.minor === 2 && attrs.type && attrs.type === 'date' && ngModel) {
  988. ngModel.$formatters.push(function (modelValue) {
  989. ngModel.$setValidity(null,(!modelValue || !isNaN(modelValue.getTime())));
  990. return $filter('date')(modelValue, 'yyyy-MM-dd');
  991. });
  992. ngModel.$parsers.push(function (viewValue) {
  993. if (viewValue && viewValue.length > 0) {
  994. var dateValue = parseDateString(viewValue);
  995. ngModel.$setValidity(null, (dateValue && !isNaN(dateValue.getTime())));
  996. return dateValue;
  997. }
  998. else {
  999. ngModel.$setValidity(null, true);
  1000. return null;
  1001. }
  1002. });
  1003. }
  1004. }
  1005. };
  1006. }]);
  1007. /**
  1008. * @ngdoc directive
  1009. * @name ui.grid.edit.directive:uiGridEditDropdown
  1010. * @element div
  1011. * @restrict A
  1012. *
  1013. * @description dropdown editor for editable fields.
  1014. * Provides EndEdit and CancelEdit events
  1015. *
  1016. * Events that end editing:
  1017. * blur and enter keydown, and any left/right nav
  1018. *
  1019. * Events that cancel editing:
  1020. * - Esc keydown
  1021. *
  1022. */
  1023. module.directive('uiGridEditDropdown',
  1024. ['uiGridConstants', 'uiGridEditConstants', '$timeout',
  1025. function (uiGridConstants, uiGridEditConstants, $timeout) {
  1026. return {
  1027. require: ['?^uiGrid', '?^uiGridRenderContainer'],
  1028. scope: true,
  1029. compile: function () {
  1030. return {
  1031. pre: function ($scope, $elm, $attrs) {
  1032. },
  1033. post: function ($scope, $elm, $attrs, controllers) {
  1034. var uiGridCtrl = controllers[0];
  1035. var renderContainerCtrl = controllers[1];
  1036. //set focus at start of edit
  1037. $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function () {
  1038. $timeout(function(){
  1039. $elm[0].focus();
  1040. });
  1041. $elm[0].style.width = ($elm[0].parentElement.offsetWidth - 1) + 'px';
  1042. $elm.on('blur', function (evt) {
  1043. $scope.stopEdit(evt);
  1044. });
  1045. });
  1046. $scope.stopEdit = function (evt) {
  1047. // no need to validate a dropdown - invalid values shouldn't be
  1048. // available in the list
  1049. $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
  1050. };
  1051. $elm.on('keydown', function (evt) {
  1052. switch (evt.keyCode) {
  1053. case uiGridConstants.keymap.ESC:
  1054. evt.stopPropagation();
  1055. $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT);
  1056. break;
  1057. }
  1058. if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
  1059. evt.uiGridTargetRenderContainerId = renderContainerCtrl.containerId;
  1060. if (uiGridCtrl.cellNav.handleKeyDown(evt) !== null) {
  1061. $scope.stopEdit(evt);
  1062. }
  1063. }
  1064. else {
  1065. //handle enter and tab for editing not using cellNav
  1066. switch (evt.keyCode) {
  1067. case uiGridConstants.keymap.ENTER: // Enter (Leave Field)
  1068. case uiGridConstants.keymap.TAB:
  1069. evt.stopPropagation();
  1070. evt.preventDefault();
  1071. $scope.stopEdit(evt);
  1072. break;
  1073. }
  1074. }
  1075. return true;
  1076. });
  1077. $scope.$on('$destroy', function unbindEvents() {
  1078. // unbind jquery events to prevent memory leaks
  1079. $elm.off();
  1080. });
  1081. }
  1082. };
  1083. }
  1084. };
  1085. }]);
  1086. /**
  1087. * @ngdoc directive
  1088. * @name ui.grid.edit.directive:uiGridEditFileChooser
  1089. * @element div
  1090. * @restrict A
  1091. *
  1092. * @description input editor directive for editable fields.
  1093. * Provides EndEdit and CancelEdit events
  1094. *
  1095. * Events that end editing:
  1096. * blur and enter keydown
  1097. *
  1098. * Events that cancel editing:
  1099. * - Esc keydown
  1100. *
  1101. */
  1102. module.directive('uiGridEditFileChooser',
  1103. ['gridUtil', 'uiGridConstants', 'uiGridEditConstants',
  1104. function (gridUtil, uiGridConstants, uiGridEditConstants) {
  1105. return {
  1106. scope: true,
  1107. require: ['?^uiGrid', '?^uiGridRenderContainer'],
  1108. compile: function () {
  1109. return {
  1110. pre: function ($scope, $elm, $attrs) {
  1111. },
  1112. post: function ($scope, $elm) {
  1113. function handleFileSelect(event) {
  1114. var target = event.srcElement || event.target;
  1115. if (target && target.files && target.files.length > 0) {
  1116. /**
  1117. * @ngdoc property
  1118. * @name editFileChooserCallback
  1119. * @propertyOf ui.grid.edit.api:ColumnDef
  1120. * @description A function that should be called when any files have been chosen
  1121. * by the user. You should use this to process the files appropriately for your
  1122. * application.
  1123. *
  1124. * It passes the gridCol, the gridRow (from which you can get gridRow.entity),
  1125. * and the files. The files are in the format as returned from the file chooser,
  1126. * an array of files, with each having useful information such as:
  1127. * - `files[0].lastModifiedDate`
  1128. * - `files[0].name`
  1129. * - `files[0].size` (appears to be in bytes)
  1130. * - `files[0].type` (MIME type by the looks)
  1131. *
  1132. * Typically you would do something with these files - most commonly you would
  1133. * use the filename or read the file itself in. The example function does both.
  1134. *
  1135. * @example
  1136. * <pre>
  1137. * editFileChooserCallBack: function(gridRow, gridCol, files ){
  1138. * // ignore all but the first file, it can only choose one anyway
  1139. * // set the filename into this column
  1140. * gridRow.entity.filename = file[0].name;
  1141. *
  1142. * // read the file and set it into a hidden column, which we may do stuff with later
  1143. * var setFile = function(fileContent){
  1144. * gridRow.entity.file = fileContent.currentTarget.result;
  1145. * };
  1146. * var reader = new FileReader();
  1147. * reader.onload = setFile;
  1148. * reader.readAsText( files[0] );
  1149. * }
  1150. * </pre>
  1151. */
  1152. if ( typeof($scope.col.colDef.editFileChooserCallback) === 'function' ) {
  1153. $scope.col.colDef.editFileChooserCallback($scope.row, $scope.col, target.files);
  1154. } else {
  1155. gridUtil.logError('You need to set colDef.editFileChooserCallback to use the file chooser');
  1156. }
  1157. target.form.reset();
  1158. $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
  1159. } else {
  1160. $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT);
  1161. }
  1162. $elm[0].removeEventListener('change', handleFileSelect, false);
  1163. }
  1164. $elm[0].addEventListener('change', handleFileSelect, false);
  1165. $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function () {
  1166. $elm[0].focus();
  1167. $elm[0].select();
  1168. $elm.on('blur', function () {
  1169. $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
  1170. $elm.off();
  1171. });
  1172. });
  1173. }
  1174. };
  1175. }
  1176. };
  1177. }]);
  1178. })();