From bd21cad28667ac8b65e3a8562f982fedddd9b555 Mon Sep 17 00:00:00 2001
From: "Portugal, Marcelo" Note that IE9 compatibility is marginal - the base functions all work but performance is poor in some cases,
-and some behaviour is not as desired. We have limited ability to control some of this, but have decided to retain IE9
-in the supported list due to the small number of organizations for whom this is critical. If using on IE9 we
+and some behaviour is not as desired. We have limited ability to control some of this. If using on IE9 we
recommend testing your specific use cases to verify all your desired functions work adequately.Browsers
Current list of tested browsers: Sauce Labs
-
How can I sh
which would be something like:
cellTemplate: '<div class="ui-grid-cell-contents">{{grid.renderContainers.body.visibleRowCache.indexOf(row)}}</div>'
Our current testing verifies against IE9+, Edge, Chrome, Firefox, and Safari 7+. We expect that the functionality +
Our current testing verifies against IE10+, Edge, Chrome, Firefox, and Safari 8+. We expect that the functionality is compatible with any HTML5 compliant and Javascript enabled browser. Refer preReqs. Note that IE9 compatibility is marginal - the base functions all work but performance is poor in some cases, and some behaviour is not - as desired. We have limited ability to control some of this, but have decided to retain IE9 in the supported list due to - the small number of organisations for whom this is critical. If using on IE9 we recommend testing your specific use cases + as desired. We have limited ability to control some of this. If using on IE9 we recommend testing your specific use cases to verify all your desired functions work adequately.
Our current testing uses angular 1.4 - 1.6. We intend to remain compatible with all forward versions of 1.6. +
Our current testing uses angular 1.4 - 1.7. We intend to remain compatible with all forward versions of 1.7. Refer preReqs
Refer also http://stackoverflow.com/questions/29298968/increase-width-of-column-in-ui-grid
diff --git a/index.html b/index.html index 165c16e4f..b1085f6d1 100644 --- a/index.html +++ b/index.html @@ -76,11 +76,11 @@++ * Will become: + *+ ++
++ ++ ++
+ ++ * Will become: + *
++ + * Note: This behavior is slightly different for the {@link ui.grid.directive:uiGridOneBindIdGrid uiGridOneBindIdGrid} + * and {@link ui.grid.directive:uiGridOneBindAriaLabelledbyGrid uiGridOneBindAriaLabelledbyGrid} directives. + * + */ + //https://github.com/joshkurz/Black-Belt-AngularJS-Directives/blob/master/directives/Optimization/oneBind.js + var oneBinders = angular.module('ui.grid'); + angular.forEach([ + /** + * @ngdoc directive + * @name ui.grid.directive:uiGridOneBindSrc + * @memberof ui.grid.directive:uiGridOneBind + * @element img + * @restrict A + * @param {String} uiGridOneBindSrc The angular string you want to bind. Does not support interpolation. Don't useAdd this text+
{{scopeElt}}
instead use scopeElt
.
+ * @description One time binding for the src dom tag.
+ *
+ */
+ {tag: 'Src', method: 'attr'},
+ /**
+ * @ngdoc directive
+ * @name ui.grid.directive:uiGridOneBindText
+ * @element div
+ * @restrict A
+ * @param {String} uiGridOneBindText The angular string you want to bind. Does not support interpolation. Don't use {{scopeElt}}
instead use scopeElt
.
+ * @description One time binding for the text dom tag.
+ */
+ {tag: 'Text', method: 'text'},
+ /**
+ * @ngdoc directive
+ * @name ui.grid.directive:uiGridOneBindHref
+ * @element div
+ * @restrict A
+ * @param {String} uiGridOneBindHref The angular string you want to bind. Does not support interpolation. Don't use {{scopeElt}}
instead use scopeElt
.
+ * @description One time binding for the href dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
+ */
+ {tag: 'Href', method: 'attr'},
+ /**
+ * @ngdoc directive
+ * @name ui.grid.directive:uiGridOneBindClass
+ * @element div
+ * @restrict A
+ * @param {String} uiGridOneBindClass The angular string you want to bind. Does not support interpolation. Don't use {{scopeElt}}
instead use scopeElt
.
+ * @param {Object} uiGridOneBindClass The object that you want to bind. At least one of the values in the object must be something other than null or undefined for the watcher to be removed.
+ * this is to prevent the watcher from being removed before the scope is initialized.
+ * @param {Array} uiGridOneBindClass An array of classes to bind to this element.
+ * @description One time binding for the class dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
+ */
+ {tag: 'Class', method: 'addClass'},
+ /**
+ * @ngdoc directive
+ * @name ui.grid.directive:uiGridOneBindHtml
+ * @element div
+ * @restrict A
+ * @param {String} uiGridOneBindHtml The angular string you want to bind. Does not support interpolation. Don't use {{scopeElt}}
instead use scopeElt
.
+ * @description One time binding for the html method on a dom element. For more information see {@link ui.grid.directive:uiGridOneBind}.
+ */
+ {tag: 'Html', method: 'html'},
+ /**
+ * @ngdoc directive
+ * @name ui.grid.directive:uiGridOneBindAlt
+ * @element div
+ * @restrict A
+ * @param {String} uiGridOneBindAlt The angular string you want to bind. Does not support interpolation. Don't use {{scopeElt}}
instead use scopeElt
.
+ * @description One time binding for the alt dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
+ */
+ {tag: 'Alt', method: 'attr'},
+ /**
+ * @ngdoc directive
+ * @name ui.grid.directive:uiGridOneBindStyle
+ * @element div
+ * @restrict A
+ * @param {String} uiGridOneBindStyle The angular string you want to bind. Does not support interpolation. Don't use {{scopeElt}}
instead use scopeElt
.
+ * @description One time binding for the style dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
+ */
+ {tag: 'Style', method: 'css'},
+ /**
+ * @ngdoc directive
+ * @name ui.grid.directive:uiGridOneBindValue
+ * @element div
+ * @restrict A
+ * @param {String} uiGridOneBindValue The angular string you want to bind. Does not support interpolation. Don't use {{scopeElt}}
instead use scopeElt
.
+ * @description One time binding for the value dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
+ */
+ {tag: 'Value', method: 'attr'},
+ /**
+ * @ngdoc directive
+ * @name ui.grid.directive:uiGridOneBindId
+ * @element div
+ * @restrict A
+ * @param {String} uiGridOneBindId The angular string you want to bind. Does not support interpolation. Don't use {{scopeElt}}
instead use scopeElt
.
+ * @description One time binding for the value dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
+ */
+ {tag: 'Id', method: 'attr'},
+ /**
+ * @ngdoc directive
+ * @name ui.grid.directive:uiGridOneBindIdGrid
+ * @element div
+ * @restrict A
+ * @param {String} uiGridOneBindIdGrid The angular string you want to bind. Does not support interpolation. Don't use {{scopeElt}}
instead use scopeElt
.
+ * @description One time binding for the id dom tag.
+ * {{scopeElt}}
instead use scopeElt
.
+ * @description One time binding for the title dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
+ */
+ {tag: 'Title', method: 'attr'},
+ /**
+ * @ngdoc directive
+ * @name ui.grid.directive:uiGridOneBindAriaLabel
+ * @element div
+ * @restrict A
+ * @param {String} uiGridOneBindAriaLabel The angular string you want to bind. Does not support interpolation. Don't use {{scopeElt}}
instead use scopeElt
.
+ * @description One time binding for the aria-label dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
+ *+ ++ * Will become: + *
+ ++ */ + {tag: 'Label', method: 'attr', aria:true}, + /** + * @ngdoc directive + * @name ui.grid.directive:uiGridOneBindAriaLabelledby + * @element div + * @restrict A + * @param {String} uiGridOneBindAriaLabelledby The angular string you want to bind. Does not support interpolation. Don't use
{{scopeElt}}
instead use scopeElt
.
+ * @description One time binding for the aria-labelledby dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
+ *+ ++ * Will become: + *
+ ++ */ + {tag: 'Labelledby', method: 'attr', aria:true}, + /** + * @ngdoc directive + * @name ui.grid.directive:uiGridOneBindAriaLabelledbyGrid + * @element div + * @restrict A + * @param {String} uiGridOneBindAriaLabelledbyGrid The angular string you want to bind. Does not support interpolation. Don't use
{{scopeElt}}
instead use scopeElt
.
+ * @description One time binding for the aria-labelledby dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
+ * Works somewhat like {@link ui.grid.directive:uiGridOneBindIdGrid} however this one supports a list of ids (seperated by a space) and will dynamically add the
+ * grid id to each one.
+ *+ ++ * Will become ([grid.id] will be replaced by the actual grid id): + *
+ ++ */ + {tag: 'Labelledby', directiveName:'LabelledbyGrid', appendGridId:true, method: 'attr', aria:true}, + /** + * @ngdoc directive + * @name ui.grid.directive:uiGridOneBindAriaDescribedby + * @element ANY + * @restrict A + * @param {String} uiGridOneBindAriaDescribedby The angular string you want to bind. Does not support interpolation. Don't use
{{scopeElt}}
instead use scopeElt
.
+ * @description One time binding for the aria-describedby dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
+ *+ ++ * Will become: + *
+ ++ */ + {tag: 'Describedby', method: 'attr', aria:true}, + /** + * @ngdoc directive + * @name ui.grid.directive:uiGridOneBindAriaDescribedbyGrid + * @element ANY + * @restrict A + * @param {String} uiGridOneBindAriaDescribedbyGrid The angular string you want to bind. Does not support interpolation. Don't use
{{scopeElt}}
instead use scopeElt
.
+ * @description One time binding for the aria-labelledby dom tag. For more information see {@link ui.grid.directive:uiGridOneBind}.
+ * Works somewhat like {@link ui.grid.directive:uiGridOneBindIdGrid} however this one supports a list of ids (seperated by a space) and will dynamically add the
+ * grid id to each one.
+ *+ ++ * Will become ([grid.id] will be replaced by the actual grid id): + *
+ ++ */ + {tag: 'Describedby', directiveName:'DescribedbyGrid', appendGridId:true, method: 'attr', aria:true}], + function(v){ + + var baseDirectiveName = 'uiGridOneBind'; + //If it is an aria tag then append the aria label seperately + //This is done because the aria tags are formatted aria-* and the directive name can't have a '-' character in it. + //If the diretiveName has to be overridden then it does so here. This is because the tag being modified and the directive sometimes don't match up. + var directiveName = (v.aria ? baseDirectiveName + 'Aria' : baseDirectiveName) + (v.directiveName ? v.directiveName : v.tag); + oneBinders.directive(directiveName, ['gridUtil', function(gridUtil){ + return { + restrict: 'A', + require: ['?uiGrid','?^uiGrid'], + link: function(scope, iElement, iAttrs, controllers){ + /* Appends the grid id to the beginnig of the value. */ + var appendGridId = function(val){ + var grid; //Get an instance of the grid if its available + //If its available in the scope then we don't need to try to find it elsewhere + if (scope.grid) { + grid = scope.grid; + } + //Another possible location to try to find the grid + else if (scope.col && scope.col.grid){ + grid = scope.col.grid; + } + //Last ditch effort: Search through the provided controllers. + else if (!controllers.some( //Go through the controllers till one has the element we need + function(controller){ + if (controller && controller.grid) { + grid = controller.grid; + return true; //We've found the grid + } + })){ + //We tried our best to find it for you + gridUtil.logError("["+directiveName+"] A valid grid could not be found to bind id. Are you using this directive " + + "within the correct scope? Trying to generate id: [gridID]-" + val); + throw new Error("No valid grid could be found"); + } + + if (grid){ + var idRegex = new RegExp(grid.id.toString()); + //If the grid id hasn't been appended already in the template declaration + if (!idRegex.test(val)){ + val = grid.id.toString() + '-' + val; + } + } + return val; + }; + + // The watch returns a function to remove itself. + var rmWatcher = scope.$watch(iAttrs[directiveName], function(newV){ + if (newV){ + //If we are trying to add an id element then we also apply the grid id if it isn't already there + if (v.appendGridId) { + var newIdString = null; + //Append the id to all of the new ids. + angular.forEach( newV.split(' '), function(s){ + newIdString = (newIdString ? (newIdString + ' ') : '') + appendGridId(s); + }); + newV = newIdString; + } + + // Append this newValue to the dom element. + switch (v.method) { + case 'attr': //The attr method takes two paraams the tag and the value + if (v.aria) { + //If it is an aria element then append the aria prefix + iElement[v.method]('aria-' + v.tag.toLowerCase(),newV); + } else { + iElement[v.method](v.tag.toLowerCase(),newV); + } + break; + case 'addClass': + //Pulled from https://github.com/Pasvaz/bindonce/blob/master/bindonce.js + if (angular.isObject(newV) && !angular.isArray(newV)) { + var results = []; + var nonNullFound = false; //We don't want to remove the binding unless the key is actually defined + angular.forEach(newV, function (value, index) { + if (value !== null && typeof(value) !== "undefined"){ + nonNullFound = true; //A non null value for a key was found so the object must have been initialized + if (value) {results.push(index);} + } + }); + //A non null value for a key wasn't found so assume that the scope values haven't been fully initialized + if (!nonNullFound){ + return; // If not initialized then the watcher should not be removed yet. + } + newV = results; + } + + if (newV) { + iElement.addClass(angular.isArray(newV) ? newV.join(' ') : newV); + } else { + return; + } + break; + default: + iElement[v.method](newV); + break; + } + + //Removes the watcher on itself after the bind + rmWatcher(); + } + // True ensures that equality is determined using angular.equals instead of === + }, true); //End rm watchers + } //End compile function + }; //End directive return + } // End directive function + ]); //End directive + }); // End angular foreach +})(); + +(function () { + 'use strict'; + + var module = angular.module('ui.grid'); + + module.directive('uiGridRenderContainer', ['$timeout', '$document', 'uiGridConstants', 'gridUtil', 'ScrollEvent', + function($timeout, $document, uiGridConstants, gridUtil, ScrollEvent) { + return { + replace: true, + transclude: true, + templateUrl: 'ui-grid/uiGridRenderContainer', + require: ['^uiGrid', 'uiGridRenderContainer'], + scope: { + containerId: '=', + rowContainerName: '=', + colContainerName: '=', + bindScrollHorizontal: '=', + bindScrollVertical: '=', + enableVerticalScrollbar: '=', + enableHorizontalScrollbar: '=' + }, + controller: 'uiGridRenderContainer as RenderContainer', + compile: function () { + return { + pre: function prelink($scope, $elm, $attrs, controllers) { + + var uiGridCtrl = controllers[0]; + var containerCtrl = controllers[1]; + var grid = $scope.grid = uiGridCtrl.grid; + + // Verify that the render container for this element exists + if (!$scope.rowContainerName) { + throw new Error("No row render container name specified"); + } + if (!$scope.colContainerName) { + throw new Error("No column render container name specified"); + } + + if (!grid.renderContainers[$scope.rowContainerName]) { + throw new Error("Row render container '" + $scope.rowContainerName + "' is not registered."); + } + if (!grid.renderContainers[$scope.colContainerName]) { + throw new Error("Column render container '" + $scope.colContainerName + "' is not registered."); + } + + var rowContainer = $scope.rowContainer = grid.renderContainers[$scope.rowContainerName]; + var colContainer = $scope.colContainer = grid.renderContainers[$scope.colContainerName]; + + containerCtrl.containerId = $scope.containerId; + containerCtrl.rowContainer = rowContainer; + containerCtrl.colContainer = colContainer; + }, + post: function postlink($scope, $elm, $attrs, controllers) { + + var uiGridCtrl = controllers[0]; + var containerCtrl = controllers[1]; + + var grid = uiGridCtrl.grid; + var rowContainer = containerCtrl.rowContainer; + var colContainer = containerCtrl.colContainer; + var scrollTop = null; + var scrollLeft = null; + + + var renderContainer = grid.renderContainers[$scope.containerId]; + + // Put the container name on this element as a class + $elm.addClass('ui-grid-render-container-' + $scope.containerId); + + // Scroll the render container viewport when the mousewheel is used + gridUtil.on.mousewheel($elm, function (event) { + var scrollEvent = new ScrollEvent(grid, rowContainer, colContainer, ScrollEvent.Sources.RenderContainerMouseWheel); + if (event.deltaY !== 0) { + var scrollYAmount = event.deltaY * -1 * event.deltaFactor; + + scrollTop = containerCtrl.viewport[0].scrollTop; + + // Get the scroll percentage + scrollEvent.verticalScrollLength = rowContainer.getVerticalScrollLength(); + var scrollYPercentage = (scrollTop + scrollYAmount) / scrollEvent.verticalScrollLength; + + // If we should be scrolled 100%, make sure the scrollTop matches the maximum scroll length + // Viewports that have "overflow: hidden" don't let the mousewheel scroll all the way to the bottom without this check + if (scrollYPercentage >= 1 && scrollTop < scrollEvent.verticalScrollLength) { + containerCtrl.viewport[0].scrollTop = scrollEvent.verticalScrollLength; + } + + // Keep scrollPercentage within the range 0-1. + if (scrollYPercentage < 0) { scrollYPercentage = 0; } + else if (scrollYPercentage > 1) { scrollYPercentage = 1; } + + scrollEvent.y = { percentage: scrollYPercentage, pixels: scrollYAmount }; + } + if (event.deltaX !== 0) { + var scrollXAmount = event.deltaX * event.deltaFactor; + + // Get the scroll percentage + scrollLeft = gridUtil.normalizeScrollLeft(containerCtrl.viewport, grid); + scrollEvent.horizontalScrollLength = (colContainer.getCanvasWidth() - colContainer.getViewportWidth()); + var scrollXPercentage = (scrollLeft + scrollXAmount) / scrollEvent.horizontalScrollLength; + + // Keep scrollPercentage within the range 0-1. + if (scrollXPercentage < 0) { scrollXPercentage = 0; } + else if (scrollXPercentage > 1) { scrollXPercentage = 1; } + + scrollEvent.x = { percentage: scrollXPercentage, pixels: scrollXAmount }; + } + + // Let the parent container scroll if the grid is already at the top/bottom + if ((event.deltaY !== 0 && (scrollEvent.atTop(scrollTop) || scrollEvent.atBottom(scrollTop))) || + (event.deltaX !== 0 && (scrollEvent.atLeft(scrollLeft) || scrollEvent.atRight(scrollLeft)))) { + //parent controller scrolls + } + else { + event.preventDefault(); + event.stopPropagation(); + scrollEvent.fireThrottledScrollingEvent('', scrollEvent); + } + + }); + + $elm.bind('$destroy', function() { + $elm.unbind('keydown'); + + ['touchstart', 'touchmove', 'touchend','keydown', 'wheel', 'mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'].forEach(function (eventName) { + $elm.unbind(eventName); + }); + }); + + // TODO(c0bra): Handle resizing the inner canvas based on the number of elements + function update() { + var ret = ''; + + var canvasWidth = colContainer.canvasWidth; + var viewportWidth = colContainer.getViewportWidth(); + + var canvasHeight = rowContainer.getCanvasHeight(); + + //add additional height for scrollbar on left and right container + //if ($scope.containerId !== 'body') { + // canvasHeight -= grid.scrollbarHeight; + //} + + var viewportHeight = rowContainer.getViewportHeight(); + //shorten the height to make room for a scrollbar placeholder + if (colContainer.needsHScrollbarPlaceholder()) { + viewportHeight -= grid.scrollbarHeight; + } + + var headerViewportWidth, + footerViewportWidth; + headerViewportWidth = footerViewportWidth = colContainer.getHeaderViewportWidth(); + + // Set canvas dimensions + ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-canvas { width: ' + canvasWidth + 'px; height: ' + canvasHeight + 'px; }'; + + ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-header-canvas { width: ' + (canvasWidth + grid.scrollbarWidth) + 'px; }'; + + if (renderContainer.explicitHeaderCanvasHeight) { + // get height from body container + var reHCHeight = document.querySelector( + '.grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-body .ui-grid-header-canvas'); + + if (reHCHeight) { + renderContainer.explicitHeaderCanvasHeight = reHCHeight.offsetHeight; + } + + ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + + ' .ui-grid-header-canvas { height: ' + renderContainer.explicitHeaderCanvasHeight + 'px; }'; + } + else { + ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + ' .ui-grid-header-canvas { height: inherit; }'; + } + + ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + + ' .ui-grid-viewport { width: ' + viewportWidth + 'px; height: ' + viewportHeight + 'px; }'; + ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + + ' .ui-grid-header-viewport { width: ' + headerViewportWidth + 'px; }'; + + ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + + ' .ui-grid-footer-canvas { width: ' + (canvasWidth + grid.scrollbarWidth) + 'px; }'; + ret += '\n .grid' + uiGridCtrl.grid.id + ' .ui-grid-render-container-' + $scope.containerId + + ' .ui-grid-footer-viewport { width: ' + footerViewportWidth + 'px; }'; + + return ret; + } + + uiGridCtrl.grid.registerStyleComputation({ + priority: 6, + func: update + }); + } + }; + } + }; + + }]); + + module.controller('uiGridRenderContainer', ['$scope', 'gridUtil', function ($scope, gridUtil) { + + }]); + +})(); + +(function(){ + 'use strict'; + + angular.module('ui.grid').directive('uiGridRow', ['gridUtil', function(gridUtil) { + return { + replace: true, + // priority: 2001, + // templateUrl: 'ui-grid/ui-grid-row', + require: ['^uiGrid', '^uiGridRenderContainer'], + scope: { + row: '=uiGridRow', + //rowRenderIndex is added to scope to give the true visual index of the row to any directives that need it + rowRenderIndex: '=' + }, + compile: function() { + return { + pre: function($scope, $elm, $attrs, controllers) { + var uiGridCtrl = controllers[0]; + var containerCtrl = controllers[1]; + + var grid = uiGridCtrl.grid; + + $scope.grid = uiGridCtrl.grid; + $scope.colContainer = containerCtrl.colContainer; + + // Function for attaching the template to this scope + var clonedElement, cloneScope; + function compileTemplate() { + $scope.row.getRowTemplateFn.then(function (compiledElementFn) { + // var compiledElementFn = $scope.row.compiledElementFn; + + // Create a new scope for the contents of this row, so we can destroy it later if need be + var newScope = $scope.$new(); + + compiledElementFn(newScope, function (newElm, scope) { + // If we already have a cloned element, we need to remove it and destroy its scope + if (clonedElement) { + clonedElement.remove(); + cloneScope.$destroy(); + } + + // Empty the row and append the new element + $elm.empty().append(newElm); + + // Save the new cloned element and scope + clonedElement = newElm; + cloneScope = newScope; + }); + }).catch(angular.noop); + } + + // Initially attach the compiled template to this scope + compileTemplate(); + + // If the row's compiled element function changes, we need to replace this element's contents with the new compiled template + $scope.$watch('row.getRowTemplateFn', function (newFunc, oldFunc) { + if (newFunc !== oldFunc) { + compileTemplate(); + } + }); + }, + post: function($scope, $elm, $attrs, controllers) { + + } + }; + } + }; + }]); + +})(); + +(function(){ +// 'use strict'; + + /** + * @ngdoc directive + * @name ui.grid.directive:uiGridStyle + * @element style + * @restrict A + * + * @description + * Allows us to interpolate expressions in ` + I am in a box. + + +
+ * $scope.gridOptions = { + * customScroller: function myScrolling(uiGridViewport, scrollHandler) { + * uiGridViewport.on('scroll', function myScrollingOverride(event) { + * // Do something here + * + * scrollHandler(event); + * }); + * } + * }; + *+ * @param {object} uiGridViewport Element being scrolled. (this gets passed in by the grid). + * @param {function} scrollHandler Function that needs to be called when scrolling happens. (this gets passed in by the grid). + */ + if (grid && grid.options && grid.options.customScroller) { + grid.options.customScroller($elm, scrollHandler); + } else { + $elm.on('scroll', scrollHandler); + } + + var ignoreScroll = false; + + function scrollHandler(evt) { + //Leaving in this commented code in case it can someday be used + //It does improve performance, but because the horizontal scroll is normalized, + // using this code will lead to the column header getting slightly out of line with columns + // + //if (ignoreScroll && (grid.isScrollingHorizontally || grid.isScrollingHorizontally)) { + // //don't ask for scrollTop if we just set it + // ignoreScroll = false; + // return; + //} + //ignoreScroll = true; + + var newScrollTop = $elm[0].scrollTop; + var newScrollLeft = gridUtil.normalizeScrollLeft($elm, grid); + + var vertScrollPercentage = rowContainer.scrollVertical(newScrollTop); + var horizScrollPercentage = colContainer.scrollHorizontal(newScrollLeft); + + var scrollEvent = new ScrollEvent(grid, rowContainer, colContainer, ScrollEvent.Sources.ViewPortScroll); + scrollEvent.newScrollLeft = newScrollLeft; + scrollEvent.newScrollTop = newScrollTop; + if ( horizScrollPercentage > -1 ){ + scrollEvent.x = { percentage: horizScrollPercentage }; + } + + if ( vertScrollPercentage > -1 ){ + scrollEvent.y = { percentage: vertScrollPercentage }; + } + + grid.scrollContainers($scope.$parent.containerId, scrollEvent); + } + + if ($scope.$parent.bindScrollVertical) { + grid.addVerticalScrollSync($scope.$parent.containerId, syncVerticalScroll); + } + + if ($scope.$parent.bindScrollHorizontal) { + grid.addHorizontalScrollSync($scope.$parent.containerId, syncHorizontalScroll); + grid.addHorizontalScrollSync($scope.$parent.containerId + 'header', syncHorizontalHeader); + grid.addHorizontalScrollSync($scope.$parent.containerId + 'footer', syncHorizontalFooter); + } + + function syncVerticalScroll(scrollEvent){ + containerCtrl.prevScrollArgs = scrollEvent; + var newScrollTop = scrollEvent.getNewScrollTop(rowContainer,containerCtrl.viewport); + $elm[0].scrollTop = newScrollTop; + + } + + function syncHorizontalScroll(scrollEvent){ + containerCtrl.prevScrollArgs = scrollEvent; + var newScrollLeft = scrollEvent.getNewScrollLeft(colContainer, containerCtrl.viewport); + $elm[0].scrollLeft = gridUtil.denormalizeScrollLeft(containerCtrl.viewport,newScrollLeft, grid); + } + + function syncHorizontalHeader(scrollEvent){ + var newScrollLeft = scrollEvent.getNewScrollLeft(colContainer, containerCtrl.viewport); + if (containerCtrl.headerViewport) { + containerCtrl.headerViewport.scrollLeft = gridUtil.denormalizeScrollLeft(containerCtrl.viewport,newScrollLeft, grid); + } + } + + function syncHorizontalFooter(scrollEvent){ + var newScrollLeft = scrollEvent.getNewScrollLeft(colContainer, containerCtrl.viewport); + if (containerCtrl.footerViewport) { + containerCtrl.footerViewport.scrollLeft = gridUtil.denormalizeScrollLeft(containerCtrl.viewport,newScrollLeft, grid); + } + } + + $scope.$on('$destroy', function unbindEvents() { + $elm.off(); + }); + }, + controller: ['$scope', function ($scope) { + this.rowStyle = function (index) { + var rowContainer = $scope.rowContainer; + var colContainer = $scope.colContainer; + + var styles = {}; + + if (rowContainer.currentTopRow !== 0){ + //top offset based on hidden rows count + var translateY = "translateY("+ (rowContainer.currentTopRow * rowContainer.grid.options.rowHeight) +"px)"; + styles['transform'] = translateY; + styles['-webkit-transform'] = translateY; + styles['-ms-transform'] = translateY; + } + + if (colContainer.currentFirstColumn !== 0) { + if (colContainer.grid.isRTL()) { + styles['margin-right'] = colContainer.columnOffset + 'px'; + } + else { + styles['margin-left'] = colContainer.columnOffset + 'px'; + } + } + + return styles; + }; + }] + }; + } + ]); + +})(); + +(function() { + +angular.module('ui.grid') +.directive('uiGridVisible', function uiGridVisibleAction() { + return function ($scope, $elm, $attr) { + $scope.$watch($attr.uiGridVisible, function (visible) { + // $elm.css('visibility', visible ? 'visible' : 'hidden'); + $elm[visible ? 'removeClass' : 'addClass']('ui-grid-invisible'); + }); + }; +}); + +})(); +(function () { + 'use strict'; + + angular.module('ui.grid').controller('uiGridController', ['$scope', '$element', '$attrs', 'gridUtil', '$q', 'uiGridConstants', + 'gridClassFactory', '$parse', '$compile', + function ($scope, $elm, $attrs, gridUtil, $q, uiGridConstants, + gridClassFactory, $parse, $compile) { + // gridUtil.logDebug('ui-grid controller'); + var self = this; + var deregFunctions = []; + + self.grid = gridClassFactory.createGrid($scope.uiGrid); + + //assign $scope.$parent if appScope not already assigned + self.grid.appScope = self.grid.appScope || $scope.$parent; + + $elm.addClass('grid' + self.grid.id); + self.grid.rtl = gridUtil.getStyles($elm[0])['direction'] === 'rtl'; + + + // angular.extend(self.grid.options, ); + + //all properties of grid are available on scope + $scope.grid = self.grid; + + if ($attrs.uiGridColumns) { + deregFunctions.push( $attrs.$observe('uiGridColumns', function(value) { + self.grid.options.columnDefs = angular.isString(value) ? angular.fromJson(value) : value; + self.grid.buildColumns() + .then(function(){ + self.grid.preCompileCellTemplates(); + + self.grid.refreshCanvas(true); + }).catch(angular.noop); + }) ); + } + + // prevents an error from being thrown when the array is not defined yet and fastWatch is on + function getSize(array) { + return array ? array.length : 0; + } + + // if fastWatch is set we watch only the length and the reference, not every individual object + if (self.grid.options.fastWatch) { + self.uiGrid = $scope.uiGrid; + if (angular.isString($scope.uiGrid.data)) { + deregFunctions.push( $scope.$parent.$watch($scope.uiGrid.data, dataWatchFunction) ); + deregFunctions.push( $scope.$parent.$watch(function() { + if ( self.grid.appScope[$scope.uiGrid.data] ){ + return self.grid.appScope[$scope.uiGrid.data].length; + } else { + return undefined; + } + }, dataWatchFunction) ); + } else { + deregFunctions.push( $scope.$parent.$watch(function() { return $scope.uiGrid.data; }, dataWatchFunction) ); + deregFunctions.push( $scope.$parent.$watch(function() { return getSize($scope.uiGrid.data); }, function(){ dataWatchFunction($scope.uiGrid.data); }) ); + } + deregFunctions.push( $scope.$parent.$watch(function() { return $scope.uiGrid.columnDefs; }, columnDefsWatchFunction) ); + deregFunctions.push( $scope.$parent.$watch(function() { return getSize($scope.uiGrid.columnDefs); }, function(){ columnDefsWatchFunction($scope.uiGrid.columnDefs); }) ); + } else { + if (angular.isString($scope.uiGrid.data)) { + deregFunctions.push( $scope.$parent.$watchCollection($scope.uiGrid.data, dataWatchFunction) ); + } else { + deregFunctions.push( $scope.$parent.$watchCollection(function() { return $scope.uiGrid.data; }, dataWatchFunction) ); + } + deregFunctions.push( $scope.$parent.$watchCollection(function() { return $scope.uiGrid.columnDefs; }, columnDefsWatchFunction) ); + } + + + function columnDefsWatchFunction(n, o) { + if (n && n !== o) { + self.grid.options.columnDefs = $scope.uiGrid.columnDefs; + self.grid.callDataChangeCallbacks(uiGridConstants.dataChange.COLUMN, { + orderByColumnDefs: true, + preCompileCellTemplates: true + }); + } + } + + var mostRecentData; + + function dataWatchFunction(newData) { + // gridUtil.logDebug('dataWatch fired'); + var promises = []; + + if ( self.grid.options.fastWatch ) { + if (angular.isString($scope.uiGrid.data)) { + newData = self.grid.appScope.$eval($scope.uiGrid.data); + } else { + newData = $scope.uiGrid.data; + } + } + + mostRecentData = newData; + + if (newData) { + // columns length is greater than the number of row header columns, which don't count because they're created automatically + var hasColumns = self.grid.columns.length > (self.grid.rowHeaderColumns ? self.grid.rowHeaderColumns.length : 0); + + if ( + // If we have no columns + !hasColumns && + // ... and we don't have a ui-grid-columns attribute, which would define columns for us + !$attrs.uiGridColumns && + // ... and we have no pre-defined columns + self.grid.options.columnDefs.length === 0 && + // ... but we DO have data + newData.length > 0 + ) { + // ... then build the column definitions from the data that we have + self.grid.buildColumnDefsFromData(newData); + } + + // If we haven't built columns before and either have some columns defined or some data defined + if (!hasColumns && (self.grid.options.columnDefs.length > 0 || newData.length > 0)) { + // Build the column set, then pre-compile the column cell templates + promises.push(self.grid.buildColumns() + .then(function() { + self.grid.preCompileCellTemplates(); + }).catch(angular.noop)); + } + + $q.all(promises).then(function() { + // use most recent data, rather than the potentially outdated data passed into watcher handler + self.grid.modifyRows(mostRecentData) + .then(function () { + // if (self.viewport) { + self.grid.redrawInPlace(true); + // } + + $scope.$evalAsync(function() { + self.grid.refreshCanvas(true); + self.grid.callDataChangeCallbacks(uiGridConstants.dataChange.ROW); + }); + }).catch(angular.noop); + }).catch(angular.noop); + } + } + + var styleWatchDereg = $scope.$watch(function () { return self.grid.styleComputations; }, function() { + self.grid.refreshCanvas(true); + }); + + $scope.$on('$destroy', function() { + deregFunctions.forEach( function( deregFn ){ deregFn(); }); + styleWatchDereg(); + }); + + self.fireEvent = function(eventName, args) { + args = args || {}; + + // Add the grid to the event arguments if it's not there + if (angular.isUndefined(args.grid)) { + args.grid = self.grid; + } + + $scope.$broadcast(eventName, args); + }; + + self.innerCompile = function innerCompile(elm) { + $compile(elm)($scope); + }; + }]); + +/** + * @ngdoc directive + * @name ui.grid.directive:uiGrid + * @element div + * @restrict EA + * @param {Object} uiGrid Options for the grid to use + * + * @description Create a very basic grid. + * + * @example +
+ * mySortFn = function(a, b) { + * var nulls = $scope.gridApi.core.sortHandleNulls(a, b); + * if ( nulls !== null ){ + * return nulls; + * } else { + * // your code for sorting here + * }; + *+ * @param {object} a sort value a + * @param {object} b sort value b + * @returns {number} null if there were no nulls/undefineds, otherwise returns + * a sort value that should be passed back from the sort function + * + */ + self.api.registerMethod( 'core', 'sortHandleNulls', rowSorter.handleNulls ); + + + /** + * @ngdoc function + * @name sortChanged + * @methodOf ui.grid.core.api:PublicApi + * @description The sort criteria on one or more columns has + * changed. Provides as parameters the grid and the output of + * getColumnSorting, which is an array of gridColumns + * that have sorting on them, sorted in priority order. + * + * @param {$scope} scope The scope of the controller. This is used to deregister this event when the scope is destroyed. + * @param {Function} callBack Will be called when the event is emited. The function passes back the grid and an array of + * columns with sorts on them, in priority order. + * + * @example + *
+ * gridApi.core.on.sortChanged( $scope, function(grid, sortColumns){ + * // do something + * }); + *+ */ + self.api.registerEvent( 'core', 'sortChanged' ); + + /** + * @ngdoc function + * @name columnVisibilityChanged + * @methodOf ui.grid.core.api:PublicApi + * @description The visibility of a column has changed, + * the column itself is passed out as a parameter of the event. + * + * @param {$scope} scope The scope of the controller. This is used to deregister this event when the scope is destroyed. + * @param {Function} callBack Will be called when the event is emited. The function passes back the GridCol that has changed. + * + * @example + *
+ * gridApi.core.on.columnVisibilityChanged( $scope, function (column) { + * // do something + * } ); + *+ */ + self.api.registerEvent( 'core', 'columnVisibilityChanged' ); + + /** + * @ngdoc method + * @name notifyDataChange + * @methodOf ui.grid.core.api:PublicApi + * @description Notify the grid that a data or config change has occurred, + * where that change isn't something the grid was otherwise noticing. This + * might be particularly relevant where you've changed values within the data + * and you'd like cell classes to be re-evaluated, or changed config within + * the columnDef and you'd like headerCellClasses to be re-evaluated. + * @param {string} type one of the + * {@link ui.grid.service:uiGridConstants#properties_dataChange uiGridConstants.dataChange} + * values (ALL, ROW, EDIT, COLUMN, OPTIONS), which tells us which refreshes to fire. + * + * - ALL: listeners fired on any of these events, fires listeners on all events. + * - ROW: fired when a row is added or removed. + * - EDIT: fired when the data in a cell is edited. + * - COLUMN: fired when the column definitions are modified. + * - OPTIONS: fired when the grid options are modified. + */ + self.api.registerMethod( 'core', 'notifyDataChange', this.notifyDataChange ); + + /** + * @ngdoc method + * @name clearAllFilters + * @methodOf ui.grid.core.api:PublicApi + * @description Clears all filters and optionally refreshes the visible rows. + * @param {object} refreshRows Defaults to true. + * @param {object} clearConditions Defaults to false. + * @param {object} clearFlags Defaults to false. + * @returns {promise} If `refreshRows` is true, returns a promise of the rows refreshing. + */ + self.api.registerMethod('core', 'clearAllFilters', this.clearAllFilters); + + self.registerDataChangeCallback( self.columnRefreshCallback, [uiGridConstants.dataChange.COLUMN]); + self.registerDataChangeCallback( self.processRowsCallback, [uiGridConstants.dataChange.EDIT]); + self.registerDataChangeCallback( self.updateFooterHeightCallback, [uiGridConstants.dataChange.OPTIONS]); + + self.registerStyleComputation({ + priority: 10, + func: self.getFooterStyles + }); + }; + + Grid.prototype.calcFooterHeight = function () { + if (!this.hasFooter()) { + return 0; + } + + var height = 0; + if (this.options.showGridFooter) { + height += this.options.gridFooterHeight; + } + + height += this.calcColumnFooterHeight(); + + return height; + }; + + Grid.prototype.calcColumnFooterHeight = function () { + var height = 0; + + if (this.options.showColumnFooter) { + height += this.options.columnFooterHeight; + } + + return height; + }; + + Grid.prototype.getFooterStyles = function () { + var style = '.grid' + this.id + ' .ui-grid-footer-aggregates-row { height: ' + this.options.columnFooterHeight + 'px; }'; + style += ' .grid' + this.id + ' .ui-grid-footer-info { height: ' + this.options.gridFooterHeight + 'px; }'; + return style; + }; + + Grid.prototype.hasFooter = function () { + return this.options.showGridFooter || this.options.showColumnFooter; + }; + + /** + * @ngdoc function + * @name isRTL + * @methodOf ui.grid.class:Grid + * @description Returns true if grid is RightToLeft + */ + Grid.prototype.isRTL = function () { + return this.rtl; + }; + + + /** + * @ngdoc function + * @name registerColumnBuilder + * @methodOf ui.grid.class:Grid + * @description When the build creates columns from column definitions, the columnbuilders will be called to add + * additional properties to the column. + * @param {function(colDef, col, gridOptions)} columnBuilder function to be called + */ + Grid.prototype.registerColumnBuilder = function registerColumnBuilder(columnBuilder) { + this.columnBuilders.push(columnBuilder); + }; + + /** + * @ngdoc function + * @name buildColumnDefsFromData + * @methodOf ui.grid.class:Grid + * @description Populates columnDefs from the provided data + * @param {function(colDef, col, gridOptions)} rowBuilder function to be called + */ + Grid.prototype.buildColumnDefsFromData = function (dataRows){ + this.options.columnDefs = gridUtil.getColumnsFromData(dataRows, this.options.excludeProperties); + }; + + /** + * @ngdoc function + * @name registerRowBuilder + * @methodOf ui.grid.class:Grid + * @description When the build creates rows from gridOptions.data, the rowBuilders will be called to add + * additional properties to the row. + * @param {function(row, gridOptions)} rowBuilder function to be called + */ + Grid.prototype.registerRowBuilder = function registerRowBuilder(rowBuilder) { + this.rowBuilders.push(rowBuilder); + }; + + + /** + * @ngdoc function + * @name registerDataChangeCallback + * @methodOf ui.grid.class:Grid + * @description When a data change occurs, the data change callbacks of the specified type + * will be called. The rules are: + * + * - when the data watch fires, that is considered a ROW change (the data watch only notices + * added or removed rows) + * - when the api is called to inform us of a change, the declared type of that change is used + * - when a cell edit completes, the EDIT callbacks are triggered + * - when the columnDef watch fires, the COLUMN callbacks are triggered + * - when the options watch fires, the OPTIONS callbacks are triggered + * + * For a given event: + * - ALL calls ROW, EDIT, COLUMN, OPTIONS and ALL callbacks + * - ROW calls ROW and ALL callbacks + * - EDIT calls EDIT and ALL callbacks + * - COLUMN calls COLUMN and ALL callbacks + * - OPTIONS calls OPTIONS and ALL callbacks + * + * @param {function(grid)} callback function to be called + * @param {array} types the types of data change you want to be informed of. Values from + * the {@link ui.grid.service:uiGridConstants#properties_dataChange uiGridConstants.dataChange} + * values ( ALL, EDIT, ROW, COLUMN, OPTIONS ). Optional and defaults to ALL + * @returns {function} deregister function - a function that can be called to deregister this callback + */ + Grid.prototype.registerDataChangeCallback = function registerDataChangeCallback(callback, types, _this) { + var uid = gridUtil.nextUid(); + if ( !types ){ + types = [uiGridConstants.dataChange.ALL]; + } + if ( !Array.isArray(types)){ + gridUtil.logError("Expected types to be an array or null in registerDataChangeCallback, value passed was: " + types ); + } + this.dataChangeCallbacks[uid] = { callback: callback, types: types, _this:_this }; + + var self = this; + var deregisterFunction = function() { + delete self.dataChangeCallbacks[uid]; + }; + return deregisterFunction; + }; + + /** + * @ngdoc function + * @name callDataChangeCallbacks + * @methodOf ui.grid.class:Grid + * @description Calls the callbacks based on the type of data change that + * has occurred. Always calls the ALL callbacks, calls the ROW, EDIT, COLUMN and OPTIONS callbacks if the + * event type is matching, or if the type is ALL. + * @param {string} type the type of event that occurred - one of the + * {@link ui.grid.service:uiGridConstants#properties_dataChange uiGridConstants.dataChange} + * values (ALL, ROW, EDIT, COLUMN, OPTIONS) + */ + Grid.prototype.callDataChangeCallbacks = function callDataChangeCallbacks(type, options) { + angular.forEach( this.dataChangeCallbacks, function( callback, uid ){ + if ( callback.types.indexOf( uiGridConstants.dataChange.ALL ) !== -1 || + callback.types.indexOf( type ) !== -1 || + type === uiGridConstants.dataChange.ALL ) { + if (callback._this) { + callback.callback.apply(callback._this, this, options); + } + else { + callback.callback(this, options); + } + } + }, this); + }; + + /** + * @ngdoc function + * @name notifyDataChange + * @methodOf ui.grid.class:Grid + * @description Notifies us that a data change has occurred, used in the public + * api for users to tell us when they've changed data or some other event that + * our watches cannot pick up + * @param {string} type the type of event that occurred - one of the + * uiGridConstants.dataChange values (ALL, ROW, EDIT, COLUMN, OPTIONS) + * + * - ALL: listeners fired on any of these events, fires listeners on all events. + * - ROW: fired when a row is added or removed. + * - EDIT: fired when the data in a cell is edited. + * - COLUMN: fired when the column definitions are modified. + * - OPTIONS: fired when the grid options are modified. + */ + Grid.prototype.notifyDataChange = function notifyDataChange(type) { + var constants = uiGridConstants.dataChange; + if ( type === constants.ALL || + type === constants.COLUMN || + type === constants.EDIT || + type === constants.ROW || + type === constants.OPTIONS ){ + this.callDataChangeCallbacks( type ); + } else { + gridUtil.logError("Notified of a data change, but the type was not recognised, so no action taken, type was: " + type); + } + }; + + + /** + * @ngdoc function + * @name columnRefreshCallback + * @methodOf ui.grid.class:Grid + * @description refreshes the grid when a column refresh + * is notified, which triggers handling of the visible flag. + * This is called on uiGridConstants.dataChange.COLUMN, and is + * registered as a dataChangeCallback in grid.js + * @param {object} grid The grid object. + * @param {object} options Any options passed into the callback. + */ + Grid.prototype.columnRefreshCallback = function columnRefreshCallback(grid, options){ + grid.buildColumns(options); + grid.queueGridRefresh(); + }; + + + /** + * @ngdoc function + * @name processRowsCallback + * @methodOf ui.grid.class:Grid + * @description calls the row processors, specifically + * intended to reset the sorting when an edit is called, + * registered as a dataChangeCallback on uiGridConstants.dataChange.EDIT + * @param {string} name column name + */ + Grid.prototype.processRowsCallback = function processRowsCallback( grid ){ + grid.queueGridRefresh(); + }; + + + /** + * @ngdoc function + * @name updateFooterHeightCallback + * @methodOf ui.grid.class:Grid + * @description recalculates the footer height, + * registered as a dataChangeCallback on uiGridConstants.dataChange.OPTIONS + * @param {string} name column name + */ + Grid.prototype.updateFooterHeightCallback = function updateFooterHeightCallback( grid ){ + grid.footerHeight = grid.calcFooterHeight(); + grid.columnFooterHeight = grid.calcColumnFooterHeight(); + }; + + + /** + * @ngdoc function + * @name getColumn + * @methodOf ui.grid.class:Grid + * @description returns a grid column for the column name + * @param {string} name column name + */ + Grid.prototype.getColumn = function getColumn(name) { + var columns = this.columns.filter(function (column) { + return column.colDef.name === name; + }); + return columns.length > 0 ? columns[0] : null; + }; + + /** + * @ngdoc function + * @name getColDef + * @methodOf ui.grid.class:Grid + * @description returns a grid colDef for the column name + * @param {string} name column.field + */ + Grid.prototype.getColDef = function getColDef(name) { + var colDefs = this.options.columnDefs.filter(function (colDef) { + return colDef.name === name; + }); + return colDefs.length > 0 ? colDefs[0] : null; + }; + + /** + * @ngdoc function + * @name assignTypes + * @methodOf ui.grid.class:Grid + * @description uses the first row of data to assign colDef.type for any types not defined. + */ + /** + * @ngdoc property + * @name type + * @propertyOf ui.grid.class:GridOptions.columnDef + * @description the type of the column, used in sorting. If not provided then the + * grid will guess the type. Add this only if the grid guessing is not to your + * satisfaction. One of: + * - 'string' + * - 'boolean' + * - 'number' + * - 'date' + * - 'object' + * - 'numberStr' + * Note that if you choose date, your dates should be in a javascript date type + * + */ + Grid.prototype.assignTypes = function(){ + var self = this; + self.options.columnDefs.forEach(function (colDef, index) { + + //Assign colDef type if not specified + if (!colDef.type) { + var col = new GridColumn(colDef, index, self); + var firstRow = self.rows.length > 0 ? self.rows[0] : null; + if (firstRow) { + colDef.type = gridUtil.guessType(self.getCellValue(firstRow, col)); + } + else { + colDef.type = 'string'; + } + } + }); + }; + + + /** + * @ngdoc function + * @name isRowHeaderColumn + * @methodOf ui.grid.class:Grid + * @description returns true if the column is a row Header + * @param {object} column column + */ + Grid.prototype.isRowHeaderColumn = function isRowHeaderColumn(column) { + return this.rowHeaderColumns.indexOf(column) !== -1; + }; + + /** + * @ngdoc function + * @name addRowHeaderColumn + * @methodOf ui.grid.class:Grid + * @description adds a row header column to the grid + * @param {object} colDef Column definition object. + * @param {float} order Number that indicates where the column should be placed in the grid. + * @param {boolean} stopColumnBuild Prevents the buildColumn callback from being triggered. This is useful to improve + * performance of the grid during initial load. + */ + Grid.prototype.addRowHeaderColumn = function addRowHeaderColumn(colDef, order, stopColumnBuild) { + var self = this; + + //default order + if (order === undefined) { + order = 0; + } + + var rowHeaderCol = new GridColumn(colDef, gridUtil.nextUid(), self); + rowHeaderCol.isRowHeader = true; + if (self.isRTL()) { + self.createRightContainer(); + rowHeaderCol.renderContainer = 'right'; + } + else { + self.createLeftContainer(); + rowHeaderCol.renderContainer = 'left'; + } + + // relies on the default column builder being first in array, as it is instantiated + // as part of grid creation + self.columnBuilders[0](colDef,rowHeaderCol,self.options) + .then(function(){ + rowHeaderCol.enableFiltering = false; + rowHeaderCol.enableSorting = false; + rowHeaderCol.enableHiding = false; + rowHeaderCol.headerPriority = order; + self.rowHeaderColumns.push(rowHeaderCol); + self.rowHeaderColumns = self.rowHeaderColumns.sort(function (a, b) { + return a.headerPriority - b.headerPriority; + }); + + if (!stopColumnBuild) { + self.buildColumns() + .then(function() { + self.preCompileCellTemplates(); + self.queueGridRefresh(); + }).catch(angular.noop); + } + }).catch(angular.noop); + }; + + /** + * @ngdoc function + * @name getOnlyDataColumns + * @methodOf ui.grid.class:Grid + * @description returns all columns except for rowHeader columns + */ + Grid.prototype.getOnlyDataColumns = function getOnlyDataColumns() { + var self = this; + var cols = []; + self.columns.forEach(function (col) { + if (self.rowHeaderColumns.indexOf(col) === -1) { + cols.push(col); + } + }); + return cols; + }; + + /** + * @ngdoc function + * @name buildColumns + * @methodOf ui.grid.class:Grid + * @description creates GridColumn objects from the columnDefinition. Calls each registered + * columnBuilder to further process the column + * @param {object} options An object contains options to use when building columns + * + * * **orderByColumnDefs**: defaults to **false**. When true, `buildColumns` will reorder existing columns according to the order within the column definitions. + * + * @returns {Promise} a promise to load any needed column resources + */ + Grid.prototype.buildColumns = function buildColumns(opts) { + var options = { + orderByColumnDefs: false + }; + + angular.extend(options, opts); + + // gridUtil.logDebug('buildColumns'); + var self = this; + var builderPromises = []; + var headerOffset = self.rowHeaderColumns.length; + var i; + + // Remove any columns for which a columnDef cannot be found + // Deliberately don't use forEach, as it doesn't like splice being called in the middle + // Also don't cache columns.length, as it will change during this operation + for (i = 0; i < self.columns.length; i++){ + if (!self.getColDef(self.columns[i].name)) { + self.columns.splice(i, 1); + i--; + } + } + + //add row header columns to the grid columns array _after_ columns without columnDefs have been removed + //rowHeaderColumns is ordered by priority so insert in reverse + for (var j = self.rowHeaderColumns.length - 1; j >= 0; j--) { + self.columns.unshift(self.rowHeaderColumns[j]); + } + + + + // look at each column def, and update column properties to match. If the column def + // doesn't have a column, then splice in a new gridCol + self.options.columnDefs.forEach(function (colDef, index) { + self.preprocessColDef(colDef); + var col = self.getColumn(colDef.name); + + if (!col) { + col = new GridColumn(colDef, gridUtil.nextUid(), self); + self.columns.splice(index + headerOffset, 0, col); + } + else { + // tell updateColumnDef that the column was pre-existing + col.updateColumnDef(colDef, false); + } + + self.columnBuilders.forEach(function (builder) { + builderPromises.push(builder.call(self, colDef, col, self.options)); + }); + }); + + /*** Reorder columns if necessary ***/ + if (!!options.orderByColumnDefs) { + // Create a shallow copy of the columns as a cache + var columnCache = self.columns.slice(0); + + // We need to allow for the "row headers" when mapping from the column defs array to the columns array + // If we have a row header in columns[0] and don't account for it we'll overwrite it with the column in columnDefs[0] + + // Go through all the column defs, use the shorter of columns length and colDefs.length because if a user has given two columns the same name then + // columns will be shorter than columnDefs. In this situation we'll avoid an error, but the user will still get an unexpected result + var len = Math.min(self.options.columnDefs.length, self.columns.length); + for (i = 0; i < len; i++) { + // If the column at this index has a different name than the column at the same index in the column defs... + if (self.columns[i + headerOffset].name !== self.options.columnDefs[i].name) { + // Replace the one in the cache with the appropriate column + columnCache[i + headerOffset] = self.getColumn(self.options.columnDefs[i].name); + } + else { + // Otherwise just copy over the one from the initial columns + columnCache[i + headerOffset] = self.columns[i + headerOffset]; + } + } + + // Empty out the columns array, non-destructively + self.columns.length = 0; + + // And splice in the updated, ordered columns from the cache + Array.prototype.splice.apply(self.columns, [0, 0].concat(columnCache)); + } + + return $q.all(builderPromises).then(function(){ + if (self.rows.length > 0){ + self.assignTypes(); + } + if (options.preCompileCellTemplates) { + self.preCompileCellTemplates(); + } + }).catch(angular.noop); + }; + + Grid.prototype.preCompileCellTemplate = function(col) { + var self = this; + var html = col.cellTemplate.replace(uiGridConstants.MODEL_COL_FIELD, self.getQualifiedColField(col)); + html = html.replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)'); + + col.compiledElementFn = $compile(html); + + if (col.compiledElementFnDefer) { + col.compiledElementFnDefer.resolve(col.compiledElementFn); + } + }; + +/** + * @ngdoc function + * @name preCompileCellTemplates + * @methodOf ui.grid.class:Grid + * @description precompiles all cell templates + */ + Grid.prototype.preCompileCellTemplates = function() { + var self = this; + self.columns.forEach(function (col) { + if ( col.cellTemplate ){ + self.preCompileCellTemplate( col ); + } else if ( col.cellTemplatePromise ){ + col.cellTemplatePromise.then( function() { + self.preCompileCellTemplate( col ); + }).catch(angular.noop); + } + }); + }; + + /** + * @ngdoc function + * @name getGridQualifiedColField + * @methodOf ui.grid.class:Grid + * @description Returns the $parse-able accessor for a column within its $scope + * @param {GridColumn} col col object + */ + Grid.prototype.getQualifiedColField = function (col) { + var base = 'row.entity'; + if ( col.field === uiGridConstants.ENTITY_BINDING ) { + return base; + } + return gridUtil.preEval(base + '.' + col.field); + }; + + /** + * @ngdoc function + * @name createLeftContainer + * @methodOf ui.grid.class:Grid + * @description creates the left render container if it doesn't already exist + */ + Grid.prototype.createLeftContainer = function() { + if (!this.hasLeftContainer()) { + this.renderContainers.left = new GridRenderContainer('left', this, { disableColumnOffset: true }); + } + }; + + /** + * @ngdoc function + * @name createRightContainer + * @methodOf ui.grid.class:Grid + * @description creates the right render container if it doesn't already exist + */ + Grid.prototype.createRightContainer = function() { + if (!this.hasRightContainer()) { + this.renderContainers.right = new GridRenderContainer('right', this, { disableColumnOffset: true }); + } + }; + + /** + * @ngdoc function + * @name hasLeftContainer + * @methodOf ui.grid.class:Grid + * @description returns true if leftContainer exists + */ + Grid.prototype.hasLeftContainer = function() { + return this.renderContainers.left !== undefined; + }; + + /** + * @ngdoc function + * @name hasRightContainer + * @methodOf ui.grid.class:Grid + * @description returns true if rightContainer exists + */ + Grid.prototype.hasRightContainer = function() { + return this.renderContainers.right !== undefined; + }; + + + /** + * undocumented function + * @name preprocessColDef + * @methodOf ui.grid.class:Grid + * @description defaults the name property from field to maintain backwards compatibility with 2.x + * validates that name or field is present + */ + Grid.prototype.preprocessColDef = function preprocessColDef(colDef) { + var self = this; + + if (!colDef.field && !colDef.name) { + throw new Error('colDef.name or colDef.field property is required'); + } + + //maintain backwards compatibility with 2.x + //field was required in 2.x. now name is required + if (colDef.name === undefined && colDef.field !== undefined) { + // See if the column name already exists: + var newName = colDef.field, + counter = 2; + while (self.getColumn(newName)) { + newName = colDef.field + counter.toString(); + counter++; + } + colDef.name = newName; + } + }; + + // Return a list of items that exist in the `n` array but not the `o` array. Uses optional property accessors passed as third & fourth parameters + Grid.prototype.newInN = function newInN(o, n, oAccessor, nAccessor) { + var self = this; + + var t = []; + for (var i = 0; i < n.length; i++) { + var nV = nAccessor ? n[i][nAccessor] : n[i]; + + var found = false; + for (var j = 0; j < o.length; j++) { + var oV = oAccessor ? o[j][oAccessor] : o[j]; + if (self.options.rowEquality(nV, oV)) { + found = true; + break; + } + } + if (!found) { + t.push(nV); + } + } + + return t; + }; + + /** + * @ngdoc function + * @name getRow + * @methodOf ui.grid.class:Grid + * @description returns the GridRow that contains the rowEntity + * @param {object} rowEntity the gridOptions.data array element instance + * @param {array} lookInRows [optional] the rows to look in - if not provided then + * looks in grid.rows + */ + Grid.prototype.getRow = function getRow(rowEntity, lookInRows) { + var self = this; + + lookInRows = typeof(lookInRows) === 'undefined' ? self.rows : lookInRows; + + var rows = lookInRows.filter(function (row) { + return self.options.rowEquality(row.entity, rowEntity); + }); + return rows.length > 0 ? rows[0] : null; + }; + + + /** + * @ngdoc function + * @name modifyRows + * @methodOf ui.grid.class:Grid + * @description creates or removes GridRow objects from the newRawData array. Calls each registered + * rowBuilder to further process the row + * @param {array} newRawData Modified set of data + * + * This method aims to achieve three things: + * 1. the resulting rows array is in the same order as the newRawData, we'll call + * rowsProcessors immediately after to sort the data anyway + * 2. if we have row hashing available, we try to use the rowHash to find the row + * 3. no memory leaks - rows that are no longer in newRawData need to be garbage collected + * + * The basic logic flow makes use of the newRawData, oldRows and oldHash, and creates + * the newRows and newHash + * + * ``` + * newRawData.forEach newEntity + * if (hashing enabled) + * check oldHash for newEntity + * else + * look for old row directly in oldRows + * if !oldRowFound // must be a new row + * create newRow + * append to the newRows and add to newHash + * run the processors + * ``` + * + * Rows are identified using the hashKey if configured. If not configured, then rows + * are identified using the gridOptions.rowEquality function + * + * This method is useful when trying to select rows immediately after loading data without + * using a $timeout/$interval, e.g.: + * + * $scope.gridOptions.data = someData; + * $scope.gridApi.grid.modifyRows($scope.gridOptions.data); + * $scope.gridApi.selection.selectRow($scope.gridOptions.data[0]); + * + * OR to persist row selection after data update (e.g. rows selected, new data loaded, want + * originally selected rows to be re-selected)) + */ + Grid.prototype.modifyRows = function modifyRows(newRawData) { + var self = this; + var oldRows = self.rows.slice(0); + var oldRowHash = self.rowHashMap || self.createRowHashMap(); + var allRowsSelected = true; + self.rowHashMap = self.createRowHashMap(); + self.rows.length = 0; + + newRawData.forEach( function( newEntity, i ) { + var newRow, oldRow; + + if ( self.options.enableRowHashing ){ + // if hashing is enabled, then this row will be in the hash if we already know about it + oldRow = oldRowHash.get( newEntity ); + } else { + // otherwise, manually search the oldRows to see if we can find this row + oldRow = self.getRow(newEntity, oldRows); + } + + // update newRow to have an entity + if ( oldRow ) { + newRow = oldRow; + newRow.entity = newEntity; + } + + // if we didn't find the row, it must be new, so create it + if ( !newRow ){ + newRow = self.processRowBuilders(new GridRow(newEntity, i, self)); + } + + self.rows.push( newRow ); + self.rowHashMap.put( newEntity, newRow ); + if (!newRow.isSelected) { + allRowsSelected = false; + } + }); + + if (self.selection && self.rows.length) { + self.selection.selectAll = allRowsSelected; + } + + self.assignTypes(); + + var p1 = $q.when(self.processRowsProcessors(self.rows)) + .then(function (renderableRows) { + return self.setVisibleRows(renderableRows); + }).catch(angular.noop); + + var p2 = $q.when(self.processColumnsProcessors(self.columns)) + .then(function (renderableColumns) { + return self.setVisibleColumns(renderableColumns); + }).catch(angular.noop); + + return $q.all([p1, p2]); + }; + + + /** + * Private Undocumented Method + * @name addRows + * @methodOf ui.grid.class:Grid + * @description adds the newRawData array of rows to the grid and calls all registered + * rowBuilders. this keyword will reference the grid + */ + Grid.prototype.addRows = function addRows(newRawData) { + var self = this; + + var existingRowCount = self.rows.length; + for (var i = 0; i < newRawData.length; i++) { + var newRow = self.processRowBuilders(new GridRow(newRawData[i], i + existingRowCount, self)); + + if (self.options.enableRowHashing) { + var found = self.rowHashMap.get(newRow.entity); + if (found) { + found.row = newRow; + } + } + + self.rows.push(newRow); + } + }; + + /** + * @ngdoc function + * @name processRowBuilders + * @methodOf ui.grid.class:Grid + * @description processes all RowBuilders for the gridRow + * @param {GridRow} gridRow reference to gridRow + * @returns {GridRow} the gridRow with all additional behavior added + */ + Grid.prototype.processRowBuilders = function processRowBuilders(gridRow) { + var self = this; + + self.rowBuilders.forEach(function (builder) { + builder.call(self, gridRow, self.options); + }); + + return gridRow; + }; + + /** + * @ngdoc function + * @name registerStyleComputation + * @methodOf ui.grid.class:Grid + * @description registered a styleComputation function + * + * If the function returns a value it will be appended into the grid's `
t&&(e.sort.priority-=1)}),this.sort={},this.grid.api.core.raise.sortChanged(this.grid,this.grid.getColumnSorting())},t.prototype.getColClass=function(e){var t=c.COL_CLASS_PREFIX+this.uid;return e?"."+t:t},t.prototype.isPinnedLeft=function(){return"left"===this.renderContainer},t.prototype.isPinnedRight=function(){return"right"===this.renderContainer},t.prototype.getColClassDefinition=function(){return" .grid"+this.grid.id+" "+this.getColClass(!0)+" { min-width: "+this.drawnWidth+"px; max-width: "+this.drawnWidth+"px; }"},t.prototype.getRenderContainer=function(){var e=this.renderContainer;return null!==e&&""!==e&&void 0!==e||(e="body"),this.grid.renderContainers[e]},t.prototype.showColumn=function(){this.colDef.visible=!0},t.prototype.getAggregationText=function(){if(this.colDef.aggregationHideLabel)return"";if(this.colDef.aggregationLabel)return this.colDef.aggregationLabel;switch(this.colDef.aggregationType){case c.aggregationTypes.count:return e.getSafeText("aggregation.count");case c.aggregationTypes.sum:return e.getSafeText("aggregation.sum");case c.aggregationTypes.avg:return e.getSafeText("aggregation.avg");case c.aggregationTypes.min:return e.getSafeText("aggregation.min");case c.aggregationTypes.max:return e.getSafeText("aggregation.max");default:return""}},t.prototype.getCellTemplate=function(){return this.cellTemplatePromise},t.prototype.getCompiledElementFn=function(){return this.compiledElementFnDefer.promise},t}]),angular.module("ui.grid").factory("GridOptions",["gridUtil","uiGridConstants",function(t,r){return{initialize:function(e){return e.onRegisterApi=e.onRegisterApi||angular.noop(),e.data=e.data||[],e.columnDefs=e.columnDefs||[],e.excludeProperties=e.excludeProperties||["$$hashKey"],e.enableRowHashing=!1!==e.enableRowHashing,e.rowIdentity=e.rowIdentity||function(e){return t.hashKey(e)},e.getRowIdentity=e.getRowIdentity||function(e){return e.$$hashKey},e.flatEntityAccess=!0===e.flatEntityAccess,e.showHeader=void 0===e.showHeader||e.showHeader,e.showHeader?e.headerRowHeight=void 0!==e.headerRowHeight?e.headerRowHeight:30:e.headerRowHeight=0,"string"==typeof e.rowHeight?e.rowHeight=parseInt(e.rowHeight)||30:e.rowHeight=e.rowHeight||30,e.minRowsToShow=void 0!==e.minRowsToShow?e.minRowsToShow:10,e.showGridFooter=!0===e.showGridFooter,e.showColumnFooter=!0===e.showColumnFooter,e.columnFooterHeight=void 0!==e.columnFooterHeight?e.columnFooterHeight:30,e.gridFooterHeight=void 0!==e.gridFooterHeight?e.gridFooterHeight:30,e.columnWidth=void 0!==e.columnWidth?e.columnWidth:50,e.maxVisibleColumnCount=void 0!==e.maxVisibleColumnCount?e.maxVisibleColumnCount:200,e.virtualizationThreshold=void 0!==e.virtualizationThreshold?e.virtualizationThreshold:20,e.columnVirtualizationThreshold=void 0!==e.columnVirtualizationThreshold?e.columnVirtualizationThreshold:10,e.excessRows=void 0!==e.excessRows?e.excessRows:4,e.scrollThreshold=void 0!==e.scrollThreshold?e.scrollThreshold:4,e.excessColumns=void 0!==e.excessColumns?e.excessColumns:4,e.horizontalScrollThreshold=void 0!==e.horizontalScrollThreshold?e.horizontalScrollThreshold:2,e.aggregationCalcThrottle=void 0!==e.aggregationCalcThrottle?e.aggregationCalcThrottle:500,e.wheelScrollThrottle=void 0!==e.wheelScrollThrottle?e.wheelScrollThrottle:70,e.scrollDebounce=void 0!==e.scrollDebounce?e.scrollDebounce:300,e.enableSorting=!1!==e.enableSorting,e.enableFiltering=!0===e.enableFiltering,e.enableColumnMenus=!1!==e.enableColumnMenus,e.enableVerticalScrollbar=void 0!==e.enableVerticalScrollbar?e.enableVerticalScrollbar:r.scrollbars.ALWAYS,e.enableHorizontalScrollbar=void 0!==e.enableHorizontalScrollbar?e.enableHorizontalScrollbar:r.scrollbars.ALWAYS,e.enableMinHeightCheck=!1!==e.enableMinHeightCheck,e.minimumColumnSize=void 0!==e.minimumColumnSize?e.minimumColumnSize:30,e.rowEquality=e.rowEquality||function(e,t){return e===t},e.headerTemplate=e.headerTemplate||null,e.footerTemplate=e.footerTemplate||"ui-grid/ui-grid-footer",e.gridFooterTemplate=e.gridFooterTemplate||"ui-grid/ui-grid-grid-footer",e.rowTemplate=e.rowTemplate||"ui-grid/ui-grid-row",e.gridMenuTemplate=e.gridMenuTemplate||"ui-grid/uiGridMenu",e.appScopeProvider=e.appScopeProvider||null,e}}}]),angular.module("ui.grid").factory("GridRenderContainer",["gridUtil","uiGridConstants",function(y,n){function e(e,t,r){var i=this;i.name=e,i.grid=t,i.visibleRowCache=[],i.visibleColumnCache=[],i.renderedRows=[],i.renderedColumns=[],i.prevScrollTop=0,i.prevScrolltopPercentage=0,i.prevRowScrollIndex=0,i.prevScrollLeft=0,i.prevScrollleftPercentage=0,i.prevColumnScrollIndex=0,i.columnStyles="",i.viewportAdjusters=[],i.hasHScrollbar=!1,i.hasVScrollbar=!1,i.canvasHeightShouldUpdate=!0,i.$$canvasHeight=0,r&&angular.isObject(r)&&angular.extend(i,r),t.registerStyleComputation({priority:5,func:function(){return i.updateColumnWidths(),i.columnStyles}})}return e.prototype.reset=function(){this.visibleColumnCache.length=0,this.visibleRowCache.length=0,this.renderedRows.length=0,this.renderedColumns.length=0},e.prototype.containsColumn=function(e){return-1!==this.visibleColumnCache.indexOf(e)},e.prototype.minRowsToRender=function(){for(var e=0,t=0,r=this.getViewportHeight(),i=this.visibleRowCache.length-1;t I$zz0)td&FKb3&-)Si?ckbII8pD2Pc`p||lJ@pW
z{CqN--oYMb$=IRYi5T$P($?x$b-tm=T<-#a$YlPP0PfrC0Ju6BkO0cK*w}-ZNXO&<
z6~Sw;*$?Z;cBTGTgphyC4fqf}ce)LXQ}~w>Yyjw&fDj-S&lW$cWnF9!JBmd3Y4#ku
zz^<@2*bmv4V;9PhA+N>5hd8t!4<{cwbLxbu=)c9?+BNQVeg7N6<9&-89(SU=lu1{h
z&!xFtlg#DST;9{n<2Ae "+o.getSafeText("validate.error")+" D!;P&i;Stq8C%tSI-42x{_yEfG8Ur#&eLGHx|CtGucN);
z^!Ut^`v({Q9qk3Q)47SEO!HSaonkD!7wxw3%#)LRrtCM+{xI5RJ~N*E%*+0hXnzLw
z{n_Ni^i1OO9skJK18LYCnViZ_{?qQJZ!p%l0rDSbw048FvRzE%GBbJR+tYVokUhY#
zBKf2K+i9K~8_h5`xYWbZN4*>z&VY);RV@A-(=h)B1!iK;I5qz<+rkC7OjE$U$FF~+
zcbLWI``^nb1B++aF=c?g2r-(;`9UXkiLnR@=EW>d-z>O9MNk`(uQFf&tK685%?~Z`
z_cDu%p!ye>L!p;6yIC_ rP4;FSmk2yH0hhYxd9gCv
zEQ(eCs|5TdYDbs$fQRhJW}63FCCbgWqq4HAC1Q3+J6j>cd+$E3hywRCi});r|9=6$
zJ-e)Jb1giGm2APfVdy=Fq~W!hZBe@|(j4xN+U>tc6dpDN@vYbj7OFR!%> Validators from this external service have a higher priority than default
+ * ones
+ * @param {function} externalFactoryFunction a function that accepts name and argument to pass to a
+ * validator factory and that returns an object with the same properties as
+ * you can see in {@link ui.grid.validate.service:uiGridValidateService#properties_validatorFactories validatorFactories}
+ */
+ setExternalFactoryFunction: function(externalFactoryFunction) {
+ service.externalFactoryFunction = externalFactoryFunction;
+ },
+
+ /**
+ * @ngdoc service
+ * @name clearExternalFactory
+ * @methodOf ui.grid.validate.service:uiGridValidateService
+ * @description Removes any link to external factory from this service
+ */
+ clearExternalFactory: function() {
+ delete service.externalFactoryFunction;
+ },
+
+ /**
+ * @ngdoc service
+ * @name getValidatorFromExternalFactory
+ * @methodOf ui.grid.validate.service:uiGridValidateService
+ * @description Retrieves a validator by executing a validatorFactory
+ * stored in an external service.
+ * @param {string} name the name of the validator to retrieve
+ * @param {object} argument an argument to pass to the validator factory
+ */
+ getValidatorFromExternalFactory: function(name, argument) {
+ return service.externalFactoryFunction(name, argument).validatorFactory(argument);
+ },
+
+ /**
+ * @ngdoc service
+ * @name getMessageFromExternalFactory
+ * @methodOf ui.grid.validate.service:uiGridValidateService
+ * @description Retrieves a message stored in an external service.
+ * @param {string} name the name of the validator
+ * @param {object} argument an argument to pass to the message function
+ */
+ getMessageFromExternalFactory: function(name, argument) {
+ return service.externalFactoryFunction(name, argument).messageFunction(argument);
+ },
+
+ /**
+ * @ngdoc service
+ * @name setValidator
+ * @methodOf ui.grid.validate.service:uiGridValidateService
+ * @description Adds a new validator to the service
+ * @param {string} name the name of the validator, must be unique
+ * @param {function} validatorFactory a factory that return a validatorFunction
+ * @param {function} messageFunction a function that return the error message
+ */
+ setValidator: function(name, validatorFactory, messageFunction) {
+ service.validatorFactories[name] = {
+ validatorFactory: validatorFactory,
+ messageFunction: messageFunction
+ };
+ },
+
+ /**
+ * @ngdoc service
+ * @name getValidator
+ * @methodOf ui.grid.validate.service:uiGridValidateService
+ * @description Returns a validator registered to the service
+ * or retrieved from the external factory
+ * @param {string} name the name of the validator to retrieve
+ * @param {object} argument an argument to pass to the validator factory
+ * @returns {object} the validator function
+ */
+ getValidator: function(name, argument) {
+ if (service.externalFactoryFunction) {
+ var validator = service.getValidatorFromExternalFactory(name, argument);
+ if (validator) {
+ return validator;
+ }
+ }
+ if (!service.validatorFactories[name]) {
+ throw ("Invalid validator name: " + name);
+ }
+ return service.validatorFactories[name].validatorFactory(argument);
+ },
+
+ /**
+ * @ngdoc service
+ * @name getMessage
+ * @methodOf ui.grid.validate.service:uiGridValidateService
+ * @description Returns the error message related to the validator
+ * @param {string} name the name of the validator
+ * @param {object} argument an argument to pass to the message function
+ * @returns {string} the error message related to the validator
+ */
+ getMessage: function(name, argument) {
+ if (service.externalFactoryFunction) {
+ var message = service.getMessageFromExternalFactory(name, argument);
+ if (message) {
+ return message;
+ }
+ }
+ return service.validatorFactories[name].messageFunction(argument);
+ },
+
+ /**
+ * @ngdoc service
+ * @name isInvalid
+ * @methodOf ui.grid.validate.service:uiGridValidateService
+ * @description Returns true if the cell (identified by rowEntity, colDef) is invalid
+ * @param {object} rowEntity the row entity of the cell
+ * @param {object} colDef the colDef of the cell
+ * @returns {boolean} true if the cell is invalid
+ */
+ isInvalid: function (rowEntity, colDef) {
+ return rowEntity['$$invalid'+colDef.name];
+ },
+
+ /**
+ * @ngdoc service
+ * @name setInvalid
+ * @methodOf ui.grid.validate.service:uiGridValidateService
+ * @description Makes the cell invalid by adding the proper field to the entity
+ * @param {object} rowEntity the row entity of the cell
+ * @param {object} colDef the colDef of the cell
+ */
+ setInvalid: function (rowEntity, colDef) {
+ rowEntity['$$invalid'+colDef.name] = true;
+ },
+
+ /**
+ * @ngdoc service
+ * @name setValid
+ * @methodOf ui.grid.validate.service:uiGridValidateService
+ * @description Makes the cell valid by removing the proper error field from the entity
+ * @param {object} rowEntity the row entity of the cell
+ * @param {object} colDef the colDef of the cell
+ */
+ setValid: function (rowEntity, colDef) {
+ delete rowEntity['$$invalid'+colDef.name];
+ },
+
+ /**
+ * @ngdoc service
+ * @name setError
+ * @methodOf ui.grid.validate.service:uiGridValidateService
+ * @description Adds the proper error to the entity errors field
+ * @param {object} rowEntity the row entity of the cell
+ * @param {object} colDef the colDef of the cell
+ * @param {string} validatorName the name of the validator that is failing
+ */
+ setError: function(rowEntity, colDef, validatorName) {
+ if (!rowEntity['$$errors'+colDef.name]) {
+ rowEntity['$$errors'+colDef.name] = {};
+ }
+ rowEntity['$$errors'+colDef.name][validatorName] = true;
+ },
+
+ /**
+ * @ngdoc service
+ * @name clearError
+ * @methodOf ui.grid.validate.service:uiGridValidateService
+ * @description Removes the proper error from the entity errors field
+ * @param {object} rowEntity the row entity of the cell
+ * @param {object} colDef the colDef of the cell
+ * @param {string} validatorName the name of the validator that is failing
+ */
+ clearError: function(rowEntity, colDef, validatorName) {
+ if (!rowEntity['$$errors'+colDef.name]) {
+ return;
+ }
+ if (validatorName in rowEntity['$$errors'+colDef.name]) {
+ delete rowEntity['$$errors'+colDef.name][validatorName];
+ }
+ },
+
+ /**
+ * @ngdoc function
+ * @name getErrorMessages
+ * @methodOf ui.grid.validate.service:uiGridValidateService
+ * @description returns an array of i18n-ed error messages.
+ * @param {object} rowEntity gridOptions.data[] array instance whose errors we are looking for
+ * @param {object} colDef the column whose errors we are looking for
+ * @returns {array} An array of strings containing all the error messages for the cell
+ */
+ getErrorMessages: function(rowEntity, colDef) {
+ var errors = [];
+
+ if (!rowEntity['$$errors'+colDef.name] || Object.keys(rowEntity['$$errors'+colDef.name]).length === 0) {
+ return errors;
+ }
+
+ Object.keys(rowEntity['$$errors'+colDef.name]).sort().forEach(function(validatorName) {
+ errors.push(service.getMessage(validatorName, colDef.validators[validatorName]));
+ });
+
+ return errors;
+ },
+
+ /**
+ * @ngdoc function
+ * @name getFormattedErrors
+ * @methodOf ui.grid.validate.service:uiGridValidateService
+ * @description returns the error i18n-ed and formatted in html to be shown inside the page.
+ * @param {object} rowEntity gridOptions.data[] array instance whose errors we are looking for
+ * @param {object} colDef the column whose errors we are looking for
+ * @returns {object} An object that can be used in a template (like a cellTemplate) to display the
+ * message inside the page (i.e. inside a div)
+ */
+ getFormattedErrors: function(rowEntity, colDef) {
+
+ var msgString = "";
+
+ var errors = service.getErrorMessages(rowEntity, colDef);
+
+ if (!errors.length) {
+ return;
+ }
+
+ errors.forEach(function(errorMsg) {
+ msgString += errorMsg + " ' + i18nService.getSafeText('validate.error') + ' "+i.getSafeText("validate.error")+" t&&(e.sort.priority-=1)}),this.sort={},this.grid.api.core.raise.sortChanged(this.grid,this.grid.getColumnSorting())},t.prototype.getColClass=function(e){var t=c.COL_CLASS_PREFIX+this.uid;return e?"."+t:t},t.prototype.isPinnedLeft=function(){return"left"===this.renderContainer},t.prototype.isPinnedRight=function(){return"right"===this.renderContainer},t.prototype.getColClassDefinition=function(){return" .grid"+this.grid.id+" "+this.getColClass(!0)+" { min-width: "+this.drawnWidth+"px; max-width: "+this.drawnWidth+"px; }"},t.prototype.getRenderContainer=function(){var e=this.renderContainer;return null!==e&&""!==e&&void 0!==e||(e="body"),this.grid.renderContainers[e]},t.prototype.showColumn=function(){this.colDef.visible=!0},t.prototype.getAggregationText=function(){if(this.colDef.aggregationHideLabel)return"";if(this.colDef.aggregationLabel)return this.colDef.aggregationLabel;switch(this.colDef.aggregationType){case c.aggregationTypes.count:return e.getSafeText("aggregation.count");case c.aggregationTypes.sum:return e.getSafeText("aggregation.sum");case c.aggregationTypes.avg:return e.getSafeText("aggregation.avg");case c.aggregationTypes.min:return e.getSafeText("aggregation.min");case c.aggregationTypes.max:return e.getSafeText("aggregation.max");default:return""}},t.prototype.getCellTemplate=function(){return this.cellTemplatePromise},t.prototype.getCompiledElementFn=function(){return this.compiledElementFnDefer.promise},t}]),angular.module("ui.grid").factory("GridOptions",["gridUtil","uiGridConstants",function(t,r){return{initialize:function(e){return e.onRegisterApi=e.onRegisterApi||angular.noop(),e.data=e.data||[],e.columnDefs=e.columnDefs||[],e.excludeProperties=e.excludeProperties||["$$hashKey"],e.enableRowHashing=!1!==e.enableRowHashing,e.rowIdentity=e.rowIdentity||function(e){return t.hashKey(e)},e.getRowIdentity=e.getRowIdentity||function(e){return e.$$hashKey},e.flatEntityAccess=!0===e.flatEntityAccess,e.showHeader=void 0===e.showHeader||e.showHeader,e.showHeader?e.headerRowHeight=void 0!==e.headerRowHeight?e.headerRowHeight:30:e.headerRowHeight=0,"string"==typeof e.rowHeight?e.rowHeight=parseInt(e.rowHeight)||30:e.rowHeight=e.rowHeight||30,e.minRowsToShow=void 0!==e.minRowsToShow?e.minRowsToShow:10,e.showGridFooter=!0===e.showGridFooter,e.showColumnFooter=!0===e.showColumnFooter,e.columnFooterHeight=void 0!==e.columnFooterHeight?e.columnFooterHeight:30,e.gridFooterHeight=void 0!==e.gridFooterHeight?e.gridFooterHeight:30,e.columnWidth=void 0!==e.columnWidth?e.columnWidth:50,e.maxVisibleColumnCount=void 0!==e.maxVisibleColumnCount?e.maxVisibleColumnCount:200,e.virtualizationThreshold=void 0!==e.virtualizationThreshold?e.virtualizationThreshold:20,e.columnVirtualizationThreshold=void 0!==e.columnVirtualizationThreshold?e.columnVirtualizationThreshold:10,e.excessRows=void 0!==e.excessRows?e.excessRows:4,e.scrollThreshold=void 0!==e.scrollThreshold?e.scrollThreshold:4,e.excessColumns=void 0!==e.excessColumns?e.excessColumns:4,e.horizontalScrollThreshold=void 0!==e.horizontalScrollThreshold?e.horizontalScrollThreshold:2,e.aggregationCalcThrottle=void 0!==e.aggregationCalcThrottle?e.aggregationCalcThrottle:500,e.wheelScrollThrottle=void 0!==e.wheelScrollThrottle?e.wheelScrollThrottle:70,e.scrollDebounce=void 0!==e.scrollDebounce?e.scrollDebounce:300,e.enableSorting=!1!==e.enableSorting,e.enableFiltering=!0===e.enableFiltering,e.enableColumnMenus=!1!==e.enableColumnMenus,e.enableVerticalScrollbar=void 0!==e.enableVerticalScrollbar?e.enableVerticalScrollbar:r.scrollbars.ALWAYS,e.enableHorizontalScrollbar=void 0!==e.enableHorizontalScrollbar?e.enableHorizontalScrollbar:r.scrollbars.ALWAYS,e.enableMinHeightCheck=!1!==e.enableMinHeightCheck,e.minimumColumnSize=void 0!==e.minimumColumnSize?e.minimumColumnSize:30,e.rowEquality=e.rowEquality||function(e,t){return e===t},e.headerTemplate=e.headerTemplate||null,e.footerTemplate=e.footerTemplate||"ui-grid/ui-grid-footer",e.gridFooterTemplate=e.gridFooterTemplate||"ui-grid/ui-grid-grid-footer",e.rowTemplate=e.rowTemplate||"ui-grid/ui-grid-row",e.gridMenuTemplate=e.gridMenuTemplate||"ui-grid/uiGridMenu",e.appScopeProvider=e.appScopeProvider||null,e}}}]),angular.module("ui.grid").factory("GridRenderContainer",["gridUtil","uiGridConstants",function(y,n){function e(e,t,r){var i=this;i.name=e,i.grid=t,i.visibleRowCache=[],i.visibleColumnCache=[],i.renderedRows=[],i.renderedColumns=[],i.prevScrollTop=0,i.prevScrolltopPercentage=0,i.prevRowScrollIndex=0,i.prevScrollLeft=0,i.prevScrollleftPercentage=0,i.prevColumnScrollIndex=0,i.columnStyles="",i.viewportAdjusters=[],i.hasHScrollbar=!1,i.hasVScrollbar=!1,i.canvasHeightShouldUpdate=!0,i.$$canvasHeight=0,r&&angular.isObject(r)&&angular.extend(i,r),t.registerStyleComputation({priority:5,func:function(){return i.updateColumnWidths(),i.columnStyles}})}return e.prototype.reset=function(){this.visibleColumnCache.length=0,this.visibleRowCache.length=0,this.renderedRows.length=0,this.renderedColumns.length=0},e.prototype.containsColumn=function(e){return-1!==this.visibleColumnCache.indexOf(e)},e.prototype.minRowsToRender=function(){for(var e=0,t=0,r=this.getViewportHeight(),i=this.visibleRowCache.length-1;t t&&(e.sort.priority-=1)}),this.sort={},this.grid.api.core.raise.sortChanged(this.grid,this.grid.getColumnSorting())},t.prototype.getColClass=function(e){var t=c.COL_CLASS_PREFIX+this.uid;return e?"."+t:t},t.prototype.isPinnedLeft=function(){return"left"===this.renderContainer},t.prototype.isPinnedRight=function(){return"right"===this.renderContainer},t.prototype.getColClassDefinition=function(){return" .grid"+this.grid.id+" "+this.getColClass(!0)+" { min-width: "+this.drawnWidth+"px; max-width: "+this.drawnWidth+"px; }"},t.prototype.getRenderContainer=function(){var e=this.renderContainer;return null!==e&&""!==e&&void 0!==e||(e="body"),this.grid.renderContainers[e]},t.prototype.showColumn=function(){this.colDef.visible=!0},t.prototype.getAggregationText=function(){if(this.colDef.aggregationHideLabel)return"";if(this.colDef.aggregationLabel)return this.colDef.aggregationLabel;switch(this.colDef.aggregationType){case c.aggregationTypes.count:return e.getSafeText("aggregation.count");case c.aggregationTypes.sum:return e.getSafeText("aggregation.sum");case c.aggregationTypes.avg:return e.getSafeText("aggregation.avg");case c.aggregationTypes.min:return e.getSafeText("aggregation.min");case c.aggregationTypes.max:return e.getSafeText("aggregation.max");default:return""}},t.prototype.getCellTemplate=function(){return this.cellTemplatePromise},t.prototype.getCompiledElementFn=function(){return this.compiledElementFnDefer.promise},t}]),angular.module("ui.grid").factory("GridOptions",["gridUtil","uiGridConstants",function(t,r){return{initialize:function(e){return e.onRegisterApi=e.onRegisterApi||angular.noop(),e.data=e.data||[],e.columnDefs=e.columnDefs||[],e.excludeProperties=e.excludeProperties||["$$hashKey"],e.enableRowHashing=!1!==e.enableRowHashing,e.rowIdentity=e.rowIdentity||function(e){return t.hashKey(e)},e.getRowIdentity=e.getRowIdentity||function(e){return e.$$hashKey},e.flatEntityAccess=!0===e.flatEntityAccess,e.showHeader=void 0===e.showHeader||e.showHeader,e.showHeader?e.headerRowHeight=void 0!==e.headerRowHeight?e.headerRowHeight:30:e.headerRowHeight=0,"string"==typeof e.rowHeight?e.rowHeight=parseInt(e.rowHeight)||30:e.rowHeight=e.rowHeight||30,e.minRowsToShow=void 0!==e.minRowsToShow?e.minRowsToShow:10,e.showGridFooter=!0===e.showGridFooter,e.showColumnFooter=!0===e.showColumnFooter,e.columnFooterHeight=void 0!==e.columnFooterHeight?e.columnFooterHeight:30,e.gridFooterHeight=void 0!==e.gridFooterHeight?e.gridFooterHeight:30,e.columnWidth=void 0!==e.columnWidth?e.columnWidth:50,e.maxVisibleColumnCount=void 0!==e.maxVisibleColumnCount?e.maxVisibleColumnCount:200,e.virtualizationThreshold=void 0!==e.virtualizationThreshold?e.virtualizationThreshold:20,e.columnVirtualizationThreshold=void 0!==e.columnVirtualizationThreshold?e.columnVirtualizationThreshold:10,e.excessRows=void 0!==e.excessRows?e.excessRows:4,e.scrollThreshold=void 0!==e.scrollThreshold?e.scrollThreshold:4,e.excessColumns=void 0!==e.excessColumns?e.excessColumns:4,e.horizontalScrollThreshold=void 0!==e.horizontalScrollThreshold?e.horizontalScrollThreshold:2,e.aggregationCalcThrottle=void 0!==e.aggregationCalcThrottle?e.aggregationCalcThrottle:500,e.wheelScrollThrottle=void 0!==e.wheelScrollThrottle?e.wheelScrollThrottle:70,e.scrollDebounce=void 0!==e.scrollDebounce?e.scrollDebounce:300,e.enableSorting=!1!==e.enableSorting,e.enableFiltering=!0===e.enableFiltering,e.enableColumnMenus=!1!==e.enableColumnMenus,e.enableVerticalScrollbar=void 0!==e.enableVerticalScrollbar?e.enableVerticalScrollbar:r.scrollbars.ALWAYS,e.enableHorizontalScrollbar=void 0!==e.enableHorizontalScrollbar?e.enableHorizontalScrollbar:r.scrollbars.ALWAYS,e.enableMinHeightCheck=!1!==e.enableMinHeightCheck,e.minimumColumnSize=void 0!==e.minimumColumnSize?e.minimumColumnSize:30,e.rowEquality=e.rowEquality||function(e,t){return e===t},e.headerTemplate=e.headerTemplate||null,e.footerTemplate=e.footerTemplate||"ui-grid/ui-grid-footer",e.gridFooterTemplate=e.gridFooterTemplate||"ui-grid/ui-grid-grid-footer",e.rowTemplate=e.rowTemplate||"ui-grid/ui-grid-row",e.gridMenuTemplate=e.gridMenuTemplate||"ui-grid/uiGridMenu",e.appScopeProvider=e.appScopeProvider||null,e}}}]),angular.module("ui.grid").factory("GridRenderContainer",["gridUtil","uiGridConstants",function(y,n){function e(e,t,r){var i=this;i.name=e,i.grid=t,i.visibleRowCache=[],i.visibleColumnCache=[],i.renderedRows=[],i.renderedColumns=[],i.prevScrollTop=0,i.prevScrolltopPercentage=0,i.prevRowScrollIndex=0,i.prevScrollLeft=0,i.prevScrollleftPercentage=0,i.prevColumnScrollIndex=0,i.columnStyles="",i.viewportAdjusters=[],i.hasHScrollbar=!1,i.hasVScrollbar=!1,i.canvasHeightShouldUpdate=!0,i.$$canvasHeight=0,r&&angular.isObject(r)&&angular.extend(i,r),t.registerStyleComputation({priority:5,func:function(){return i.updateColumnWidths(),i.columnStyles}})}return e.prototype.reset=function(){this.visibleColumnCache.length=0,this.visibleRowCache.length=0,this.renderedRows.length=0,this.renderedColumns.length=0},e.prototype.containsColumn=function(e){return-1!==this.visibleColumnCache.indexOf(e)},e.prototype.minRowsToRender=function(){for(var e=0,t=0,r=this.getViewportHeight(),i=this.visibleRowCache.length-1;t "+o.getSafeText("validate.error")+"
+ *
+ * To really get the full spreadsheet-like data entry, the ui.grid.cellNav module should be used. This will allow the
+ * user to key data and then tab, arrow, or enter to the cells beside or below.
+ *
+ *
+ */
+
+ var module = angular.module('ui.grid.edit', ['ui.grid']);
+
+ /**
+ * @ngdoc object
+ * @name ui.grid.edit.constant:uiGridEditConstants
+ *
+ * @description constants available in edit module
+ */
+ module.constant('uiGridEditConstants', {
+ EDITABLE_CELL_TEMPLATE: /EDITABLE_CELL_TEMPLATE/g,
+ //must be lowercase because template bulder converts to lower
+ EDITABLE_CELL_DIRECTIVE: /editable_cell_directive/g,
+ events: {
+ BEGIN_CELL_EDIT: 'uiGridEventBeginCellEdit',
+ END_CELL_EDIT: 'uiGridEventEndCellEdit',
+ CANCEL_CELL_EDIT: 'uiGridEventCancelCellEdit'
+ }
+ });
+
+ /**
+ * @ngdoc service
+ * @name ui.grid.edit.service:uiGridEditService
+ *
+ * @description Services for editing features
+ */
+ module.service('uiGridEditService', ['$q', 'uiGridConstants', 'gridUtil',
+ function ($q, uiGridConstants, gridUtil) {
+
+ var service = {
+
+ initializeGrid: function (grid) {
+
+ service.defaultGridOptions(grid.options);
+
+ grid.registerColumnBuilder(service.editColumnBuilder);
+ grid.edit = {};
+
+ /**
+ * @ngdoc object
+ * @name ui.grid.edit.api:PublicApi
+ *
+ * @description Public Api for edit feature
+ */
+ var publicApi = {
+ events: {
+ edit: {
+ /**
+ * @ngdoc event
+ * @name afterCellEdit
+ * @eventOf ui.grid.edit.api:PublicApi
+ * @description raised when cell editing is complete
+ *
+ * gridApi.edit.on.afterCellEdit(scope,function(rowEntity, colDef){})
+ *
+ * @param {object} rowEntity the options.data element that was edited
+ * @param {object} colDef the column that was edited
+ * @param {object} newValue new value
+ * @param {object} oldValue old value
+ */
+ afterCellEdit: function (rowEntity, colDef, newValue, oldValue) {
+ },
+ /**
+ * @ngdoc event
+ * @name beginCellEdit
+ * @eventOf ui.grid.edit.api:PublicApi
+ * @description raised when cell editing starts on a cell
+ *
+ * gridApi.edit.on.beginCellEdit(scope,function(rowEntity, colDef){})
+ *
+ * @param {object} rowEntity the options.data element that was edited
+ * @param {object} colDef the column that was edited
+ * @param {object} triggerEvent the event that triggered the edit. Useful to prevent losing keystrokes on some
+ * complex editors
+ */
+ beginCellEdit: function (rowEntity, colDef, triggerEvent) {
+ },
+ /**
+ * @ngdoc event
+ * @name cancelCellEdit
+ * @eventOf ui.grid.edit.api:PublicApi
+ * @description raised when cell editing is cancelled on a cell
+ *
+ * gridApi.edit.on.cancelCellEdit(scope,function(rowEntity, colDef){})
+ *
+ * @param {object} rowEntity the options.data element that was edited
+ * @param {object} colDef the column that was edited
+ */
+ cancelCellEdit: function (rowEntity, colDef) {
+ }
+ }
+ },
+ methods: {
+ edit: { }
+ }
+ };
+
+ grid.api.registerEventsFromObject(publicApi.events);
+ //grid.api.registerMethodsFromObject(publicApi.methods);
+
+ },
+
+ defaultGridOptions: function (gridOptions) {
+
+ /**
+ * @ngdoc object
+ * @name ui.grid.edit.api:GridOptions
+ *
+ * @description Options for configuring the edit feature, these are available to be
+ * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
+ */
+
+ /**
+ * @ngdoc object
+ * @name enableCellEdit
+ * @propertyOf ui.grid.edit.api:GridOptions
+ * @description If defined, sets the default value for the editable flag on each individual colDefs
+ * if their individual enableCellEdit configuration is not defined. Defaults to undefined.
+ */
+
+ /**
+ * @ngdoc object
+ * @name cellEditableCondition
+ * @propertyOf ui.grid.edit.api:GridOptions
+ * @description If specified, either a value or function to be used by all columns before editing.
+ * If false, then editing of cell is not allowed.
+ * @example
+ *
+ * function($scope, triggerEvent){
+ * //use $scope.row.entity, $scope.col.colDef and triggerEvent to determine if editing is allowed
+ * return true;
+ * }
+ *
+ */
+ gridOptions.cellEditableCondition = gridOptions.cellEditableCondition === undefined ? true : gridOptions.cellEditableCondition;
+
+ /**
+ * @ngdoc object
+ * @name editableCellTemplate
+ * @propertyOf ui.grid.edit.api:GridOptions
+ * @description If specified, cellTemplate to use as the editor for all columns.
+ *
defaults to 'ui-grid/cellTextEditor'
+ */
+
+ /**
+ * @ngdoc object
+ * @name enableCellEditOnFocus
+ * @propertyOf ui.grid.edit.api:GridOptions
+ * @description If true, then editor is invoked as soon as cell receives focus. Default false.
+ *
_requires cellNav feature and the edit feature to be enabled_
+ */
+ //enableCellEditOnFocus can only be used if cellnav module is used
+ gridOptions.enableCellEditOnFocus = gridOptions.enableCellEditOnFocus === undefined ? false : gridOptions.enableCellEditOnFocus;
+ },
+
+ /**
+ * @ngdoc service
+ * @name editColumnBuilder
+ * @methodOf ui.grid.edit.service:uiGridEditService
+ * @description columnBuilder function that adds edit properties to grid column
+ * @returns {promise} promise that will load any needed templates when resolved
+ */
+ editColumnBuilder: function (colDef, col, gridOptions) {
+
+ var promises = [];
+
+ /**
+ * @ngdoc object
+ * @name ui.grid.edit.api:ColumnDef
+ *
+ * @description Column Definition for edit feature, these are available to be
+ * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
+ */
+
+ /**
+ * @ngdoc object
+ * @name enableCellEdit
+ * @propertyOf ui.grid.edit.api:ColumnDef
+ * @description enable editing on column
+ */
+ colDef.enableCellEdit = colDef.enableCellEdit === undefined ? (gridOptions.enableCellEdit === undefined ?
+ (colDef.type !== 'object') : gridOptions.enableCellEdit) : colDef.enableCellEdit;
+
+ /**
+ * @ngdoc object
+ * @name cellEditableCondition
+ * @propertyOf ui.grid.edit.api:ColumnDef
+ * @description If specified, either a value or function evaluated before editing cell. If falsy, then editing of cell is not allowed.
+ * @example
+ *
+ * function($scope, triggerEvent){
+ * //use $scope.row.entity, $scope.col.colDef and triggerEvent to determine if editing is allowed
+ * return true;
+ * }
+ *
+ */
+ colDef.cellEditableCondition = colDef.cellEditableCondition === undefined ? gridOptions.cellEditableCondition : colDef.cellEditableCondition;
+
+ /**
+ * @ngdoc object
+ * @name editableCellTemplate
+ * @propertyOf ui.grid.edit.api:ColumnDef
+ * @description cell template to be used when editing this column. Can be Url or text template
+ *
Defaults to gridOptions.editableCellTemplate
+ */
+ if (colDef.enableCellEdit) {
+ colDef.editableCellTemplate = colDef.editableCellTemplate || gridOptions.editableCellTemplate || 'ui-grid/cellEditor';
+
+ promises.push(gridUtil.getTemplate(colDef.editableCellTemplate)
+ .then(
+ function (template) {
+ col.editableCellTemplate = template;
+ },
+ function (res) {
+ // Todo handle response error here?
+ throw new Error("Couldn't fetch/use colDef.editableCellTemplate '" + colDef.editableCellTemplate + "'");
+ }));
+ }
+
+ /**
+ * @ngdoc object
+ * @name enableCellEditOnFocus
+ * @propertyOf ui.grid.edit.api:ColumnDef
+ * @requires ui.grid.cellNav
+ * @description If true, then editor is invoked as soon as cell receives focus. Default false.
+ *
_requires both the cellNav feature and the edit feature to be enabled_
+ */
+ //enableCellEditOnFocus can only be used if cellnav module is used
+ colDef.enableCellEditOnFocus = colDef.enableCellEditOnFocus === undefined ? gridOptions.enableCellEditOnFocus : colDef.enableCellEditOnFocus;
+
+
+ /**
+ * @ngdoc string
+ * @name editModelField
+ * @propertyOf ui.grid.edit.api:ColumnDef
+ * @description a bindable string value that is used when binding to edit controls instead of colDef.field
+ *
example: You have a complex property on and object like state:{abbrev:'MS',name:'Mississippi'}. The
+ * grid should display state.name in the cell and sort/filter based on the state.name property but the editor
+ * requires the full state object.
+ *
colDef.field = 'state.name'
+ *
colDef.editModelField = 'state'
+ */
+ //colDef.editModelField
+
+ return $q.all(promises);
+ },
+
+ /**
+ * @ngdoc service
+ * @name isStartEditKey
+ * @methodOf ui.grid.edit.service:uiGridEditService
+ * @description Determines if a keypress should start editing. Decorate this service to override with your
+ * own key events. See service decorator in angular docs.
+ * @param {Event} evt keydown event
+ * @returns {boolean} true if an edit should start
+ */
+ isStartEditKey: function (evt) {
+ if (evt.metaKey ||
+ evt.keyCode === uiGridConstants.keymap.ESC ||
+ evt.keyCode === uiGridConstants.keymap.SHIFT ||
+ evt.keyCode === uiGridConstants.keymap.CTRL ||
+ evt.keyCode === uiGridConstants.keymap.ALT ||
+ evt.keyCode === uiGridConstants.keymap.WIN ||
+ evt.keyCode === uiGridConstants.keymap.CAPSLOCK ||
+
+ evt.keyCode === uiGridConstants.keymap.LEFT ||
+ (evt.keyCode === uiGridConstants.keymap.TAB && evt.shiftKey) ||
+
+ evt.keyCode === uiGridConstants.keymap.RIGHT ||
+ evt.keyCode === uiGridConstants.keymap.TAB ||
+
+ evt.keyCode === uiGridConstants.keymap.UP ||
+ (evt.keyCode === uiGridConstants.keymap.ENTER && evt.shiftKey) ||
+
+ evt.keyCode === uiGridConstants.keymap.DOWN ||
+ evt.keyCode === uiGridConstants.keymap.ENTER) {
+ return false;
+
+ }
+ return true;
+ }
+
+
+ };
+
+ return service;
+
+ }]);
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.edit.directive:uiGridEdit
+ * @element div
+ * @restrict A
+ *
+ * @description Adds editing features to the ui-grid directive.
+ *
+ * @example
+
+ * $scope.gridOptions = {
+ * columnDefs: [
+ * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor',
+ * editDropdownOptionsArray: [{code: 1, status: 'active'}, {code: 2, status: 'inactive'}],
+ * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' }
+ * ],
+ *
+ *
+ */
+ /**
+ * @ngdoc property
+ * @name editDropdownRowEntityOptionsArrayPath
+ * @propertyOf ui.grid.edit.api:ColumnDef
+ * @description a path to a property on row.entity containing an
+ * array of values in the format
+ * [ {id: xxx, value: xxx} ], which will be used to populate
+ * the edit dropdown. This can be used when the dropdown values are dependent on
+ * the backing row entity.
+ * If this property is set then editDropdownOptionsArray will be ignored.
+ * @example
+ *
+ * $scope.gridOptions = {
+ * columnDefs: [
+ * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor',
+ * editDropdownRowEntityOptionsArrayPath: 'foo.bars[0].baz',
+ * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' }
+ * ],
+ *
+ *
+ */
+ /**
+ * @ngdoc service
+ * @name editDropdownOptionsFunction
+ * @methodOf ui.grid.edit.api:ColumnDef
+ * @description a function returning an array of values in the format
+ * [ {id: xxx, value: xxx} ], which will be used to populate
+ * the edit dropdown. This can be used when the dropdown values are dependent on
+ * the backing row entity with some kind of algorithm.
+ * If this property is set then both editDropdownOptionsArray and
+ * editDropdownRowEntityOptionsArrayPath will be ignored.
+ * @param {object} rowEntity the options.data element that the returned array refers to
+ * @param {object} colDef the column that implements this dropdown
+ * @returns {object} an array of values in the format
+ * [ {id: xxx, value: xxx} ] used to populate the edit dropdown
+ * @example
+ *
+ * $scope.gridOptions = {
+ * columnDefs: [
+ * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor',
+ * editDropdownOptionsFunction: function(rowEntity, colDef) {
+ * if (rowEntity.foo === 'bar') {
+ * return [{id: 'bar1', value: 'BAR 1'},
+ * {id: 'bar2', value: 'BAR 2'},
+ * {id: 'bar3', value: 'BAR 3'}];
+ * } else {
+ * return [{id: 'foo1', value: 'FOO 1'},
+ * {id: 'foo2', value: 'FOO 2'}];
+ * }
+ * },
+ * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' }
+ * ],
+ *
+ *
+ */
+ /**
+ * @ngdoc property
+ * @name editDropdownValueLabel
+ * @propertyOf ui.grid.edit.api:ColumnDef
+ * @description the label for the "value" field
+ * in the editDropdownOptionsArray. Defaults
+ * to 'value'
+ * @example
+ *
+ * $scope.gridOptions = {
+ * columnDefs: [
+ * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor',
+ * editDropdownOptionsArray: [{code: 1, status: 'active'}, {code: 2, status: 'inactive'}],
+ * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status' }
+ * ],
+ *
+ *
+ */
+ /**
+ * @ngdoc property
+ * @name editDropdownFilter
+ * @propertyOf ui.grid.edit.api:ColumnDef
+ * @description A filter that you would like to apply to the values in the options list
+ * of the dropdown. For example if you were using angular-translate you might set this
+ * to `'translate'`
+ * @example
+ *
+ * $scope.gridOptions = {
+ * columnDefs: [
+ * {name: 'status', editableCellTemplate: 'ui-grid/dropdownEditor',
+ * editDropdownOptionsArray: [{code: 1, status: 'active'}, {code: 2, status: 'inactive'}],
+ * editDropdownIdLabel: 'code', editDropdownValueLabel: 'status', editDropdownFilter: 'translate' }
+ * ],
+ *
+ *
+ */
+ function beginEditAfterScroll(triggerEvent) {
+ // If we are already editing, then just skip this so we don't try editing twice...
+ if (inEdit) {
+ return;
+ }
+
+ if (!shouldEdit($scope.col, $scope.row, triggerEvent)) {
+ return;
+ }
+
+ var modelField = $scope.row.getQualifiedColField($scope.col);
+ if ($scope.col.colDef.editModelField) {
+ modelField = gridUtil.preEval('row.entity.' + $scope.col.colDef.editModelField);
+ }
+
+ cellModel = $parse(modelField);
+
+ //get original value from the cell
+ origCellValue = cellModel($scope);
+
+ html = $scope.col.editableCellTemplate;
+ html = html.replace(uiGridConstants.MODEL_COL_FIELD, modelField);
+ html = html.replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)');
+
+ var optionFilter = $scope.col.colDef.editDropdownFilter ? '|' + $scope.col.colDef.editDropdownFilter : '';
+ html = html.replace(uiGridConstants.CUSTOM_FILTERS, optionFilter);
+
+ var inputType = 'text';
+ switch ($scope.col.colDef.type){
+ case 'boolean':
+ inputType = 'checkbox';
+ break;
+ case 'number':
+ inputType = 'number';
+ break;
+ case 'date':
+ inputType = 'date';
+ break;
+ }
+ html = html.replace('INPUT_TYPE', inputType);
+
+ // In order to fill dropdown options we use:
+ // - A function/promise or
+ // - An array inside of row entity if no function exists or
+ // - A single array for the whole column if none of the previous exists.
+ var editDropdownOptionsFunction = $scope.col.colDef.editDropdownOptionsFunction;
+ if (editDropdownOptionsFunction) {
+ $q.when(editDropdownOptionsFunction($scope.row.entity, $scope.col.colDef))
+ .then(function(result) {
+ $scope.editDropdownOptionsArray = result;
+ });
+ } else {
+ var editDropdownRowEntityOptionsArrayPath = $scope.col.colDef.editDropdownRowEntityOptionsArrayPath;
+ if (editDropdownRowEntityOptionsArrayPath) {
+ $scope.editDropdownOptionsArray = resolveObjectFromPath($scope.row.entity, editDropdownRowEntityOptionsArrayPath);
+ }
+ else {
+ $scope.editDropdownOptionsArray = $scope.col.colDef.editDropdownOptionsArray;
+ }
+ }
+ $scope.editDropdownIdLabel = $scope.col.colDef.editDropdownIdLabel ? $scope.col.colDef.editDropdownIdLabel : 'id';
+ $scope.editDropdownValueLabel = $scope.col.colDef.editDropdownValueLabel ? $scope.col.colDef.editDropdownValueLabel : 'value';
+
+ var cellElement;
+ var createEditor = function(){
+ inEdit = true;
+ cancelBeginEditEvents();
+ var cellElement = angular.element(html);
+ $elm.append(cellElement);
+ editCellScope = $scope.$new();
+ $compile(cellElement)(editCellScope);
+ var gridCellContentsEl = angular.element($elm.children()[0]);
+ gridCellContentsEl.addClass('ui-grid-cell-contents-hidden');
+ };
+ if (!$rootScope.$$phase) {
+ $scope.$apply(createEditor);
+ } else {
+ createEditor();
+ }
+
+ //stop editing when grid is scrolled
+ var deregOnGridScroll = $scope.col.grid.api.core.on.scrollBegin($scope, function () {
+ if ($scope.grid.disableScrolling) {
+ return;
+ }
+ endEdit();
+ $scope.grid.api.edit.raise.afterCellEdit($scope.row.entity, $scope.col.colDef, cellModel($scope), origCellValue);
+ deregOnGridScroll();
+ deregOnEndCellEdit();
+ deregOnCancelCellEdit();
+ });
+
+ //end editing
+ var deregOnEndCellEdit = $scope.$on(uiGridEditConstants.events.END_CELL_EDIT, function () {
+ endEdit();
+ $scope.grid.api.edit.raise.afterCellEdit($scope.row.entity, $scope.col.colDef, cellModel($scope), origCellValue);
+ deregOnEndCellEdit();
+ deregOnGridScroll();
+ deregOnCancelCellEdit();
+ });
+
+ //cancel editing
+ var deregOnCancelCellEdit = $scope.$on(uiGridEditConstants.events.CANCEL_CELL_EDIT, function () {
+ cancelEdit();
+ deregOnCancelCellEdit();
+ deregOnGridScroll();
+ deregOnEndCellEdit();
+ });
+
+ $scope.$broadcast(uiGridEditConstants.events.BEGIN_CELL_EDIT, triggerEvent);
+ $timeout(function () {
+ // execute in a timeout to give any complex editor templates a cycle to completely render
+ $scope.grid.api.edit.raise.beginCellEdit($scope.row.entity, $scope.col.colDef, triggerEvent);
+ });
+ }
+
+ function endEdit() {
+ $scope.grid.disableScrolling = false;
+ if (!inEdit) {
+ return;
+ }
+
+ //sometimes the events can't keep up with the keyboard and grid focus is lost, so always focus
+ //back to grid here. The focus call needs to be before the $destroy and removal of the control,
+ //otherwise ng-model-options of UpdateOn: 'blur' will not work.
+ if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
+ uiGridCtrl.focus();
+ }
+
+ var gridCellContentsEl = angular.element($elm.children()[0]);
+ //remove edit element
+ editCellScope.$destroy();
+ var children = $elm.children();
+ for (var i = 1; i < children.length; i++) {
+ angular.element(children[i]).remove();
+ }
+ gridCellContentsEl.removeClass('ui-grid-cell-contents-hidden');
+ inEdit = false;
+ registerBeginEditEvents();
+ $scope.grid.api.core.notifyDataChange( uiGridConstants.dataChange.EDIT );
+ }
+
+ function cancelEdit() {
+ $scope.grid.disableScrolling = false;
+ if (!inEdit) {
+ return;
+ }
+ cellModel.assign($scope, origCellValue);
+ $scope.$apply();
+
+ $scope.grid.api.edit.raise.cancelCellEdit($scope.row.entity, $scope.col.colDef);
+ endEdit();
+ }
+
+ // resolves a string path against the given object
+ // shamelessly borrowed from
+ // http://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key
+ function resolveObjectFromPath(object, path) {
+ path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
+ path = path.replace(/^\./, ''); // strip a leading dot
+ var a = path.split('.');
+ while (a.length) {
+ var n = a.shift();
+ if (n in object) {
+ object = object[n];
+ } else {
+ return;
+ }
+ }
+ return object;
+ }
+ }
+ };
+ }]);
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.edit.directive:uiGridEditor
+ * @element div
+ * @restrict A
+ *
+ * @description input editor directive for editable fields.
+ * Provides EndEdit and CancelEdit events
+ *
+ * Events that end editing:
+ * blur and enter keydown
+ *
+ * Events that cancel editing:
+ * - Esc keydown
+ *
+ */
+ module.directive('uiGridEditor',
+ ['gridUtil', 'uiGridConstants', 'uiGridEditConstants','$timeout', 'uiGridEditService',
+ function (gridUtil, uiGridConstants, uiGridEditConstants, $timeout, uiGridEditService) {
+ return {
+ scope: true,
+ require: ['?^uiGrid', '?^uiGridRenderContainer', 'ngModel'],
+ compile: function () {
+ return {
+ pre: function ($scope, $elm, $attrs) {
+
+ },
+ post: function ($scope, $elm, $attrs, controllers) {
+ var uiGridCtrl, renderContainerCtrl, ngModel;
+ if (controllers[0]) { uiGridCtrl = controllers[0]; }
+ if (controllers[1]) { renderContainerCtrl = controllers[1]; }
+ if (controllers[2]) { ngModel = controllers[2]; }
+
+ //set focus at start of edit
+ $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function (evt,triggerEvent) {
+ // must be in a timeout since it requires a new digest cycle
+ $timeout(function () {
+ $elm[0].focus();
+ //only select text if it is not being replaced below in the cellNav viewPortKeyPress
+ if ($elm[0].select && ($scope.col.colDef.enableCellEditOnFocus || !(uiGridCtrl && uiGridCtrl.grid.api.cellNav))) {
+ $elm[0].select();
+ }
+ else {
+ //some browsers (Chrome) stupidly, imo, support the w3 standard that number, email, ...
+ //fields should not allow setSelectionRange. We ignore the error for those browsers
+ //https://www.w3.org/Bugs/Public/show_bug.cgi?id=24796
+ try {
+ $elm[0].setSelectionRange($elm[0].value.length, $elm[0].value.length);
+ }
+ catch (ex) {
+ //ignore
+ }
+ }
+ });
+
+ //set the keystroke that started the edit event
+ //we must do this because the BeginEdit is done in a different event loop than the intitial
+ //keydown event
+ //fire this event for the keypress that is received
+ if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
+ var viewPortKeyDownUnregister = uiGridCtrl.grid.api.cellNav.on.viewPortKeyPress($scope, function (evt, rowCol) {
+ if (uiGridEditService.isStartEditKey(evt)) {
+ var code = typeof evt.which === 'number' ? evt.which : evt.keyCode;
+ if (code > 0) {
+ ngModel.$setViewValue(String.fromCharCode(code), evt);
+ ngModel.$render();
+ }
+ }
+ viewPortKeyDownUnregister();
+ });
+ }
+
+ // macOS will blur the checkbox when clicked in Safari and Firefox,
+ // to get around this, we disable the blur handler on mousedown,
+ // and then focus the checkbox and re-enable the blur handler after $timeout
+ $elm.on('mousedown', function(evt) {
+ if ($elm[0].type === 'checkbox') {
+ $elm.off('blur', $scope.stopEdit);
+ $timeout(function() {
+ $elm[0].focus();
+ $elm.on('blur', $scope.stopEdit);
+ });
+ }
+ });
+
+ $elm.on('blur', $scope.stopEdit);
+ });
+
+
+ $scope.deepEdit = false;
+
+ $scope.stopEdit = function (evt) {
+ if ($scope.inputForm && !$scope.inputForm.$valid) {
+ evt.stopPropagation();
+ $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT);
+ }
+ else {
+ $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
+ }
+ $scope.deepEdit = false;
+ };
+
+
+ $elm.on('click', function (evt) {
+ if ($elm[0].type !== 'checkbox') {
+ $scope.deepEdit = true;
+ $scope.$applyAsync(function () {
+ $scope.grid.disableScrolling = true;
+ });
+ }
+ });
+
+ $elm.on('keydown', function (evt) {
+ switch (evt.keyCode) {
+ case uiGridConstants.keymap.ESC:
+ evt.stopPropagation();
+ $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT);
+ break;
+ }
+
+ if ($scope.deepEdit &&
+ (evt.keyCode === uiGridConstants.keymap.LEFT ||
+ evt.keyCode === uiGridConstants.keymap.RIGHT ||
+ evt.keyCode === uiGridConstants.keymap.UP ||
+ evt.keyCode === uiGridConstants.keymap.DOWN)) {
+ evt.stopPropagation();
+ }
+ // Pass the keydown event off to the cellNav service, if it exists
+ else if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
+ evt.uiGridTargetRenderContainerId = renderContainerCtrl.containerId;
+ if (uiGridCtrl.cellNav.handleKeyDown(evt) !== null) {
+ $scope.stopEdit(evt);
+ }
+ }
+ else {
+ //handle enter and tab for editing not using cellNav
+ switch (evt.keyCode) {
+ case uiGridConstants.keymap.ENTER: // Enter (Leave Field)
+ case uiGridConstants.keymap.TAB:
+ evt.stopPropagation();
+ evt.preventDefault();
+ $scope.stopEdit(evt);
+ break;
+ }
+ }
+
+ return true;
+ });
+
+ $scope.$on('$destroy', function unbindEvents() {
+ // unbind all jquery events in order to avoid memory leaks
+ $elm.off();
+ });
+ }
+ };
+ }
+ };
+ }]);
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.edit.directive:input
+ * @element input
+ * @restrict E
+ *
+ * @description directive to provide binding between input[date] value and ng-model for angular 1.2
+ * It is similar to input[date] directive of angular 1.3
+ *
+ * Supported date format for input is 'yyyy-MM-dd'
+ * The directive will set the $valid property of input element and the enclosing form to false if
+ * model is invalid date or value of input is entered wrong.
+ *
+ */
+ module.directive('uiGridEditor', ['$filter', function ($filter) {
+ function parseDateString(dateString) {
+ if (typeof(dateString) === 'undefined' || dateString === '') {
+ return null;
+ }
+ var parts = dateString.split('-');
+ if (parts.length !== 3) {
+ return null;
+ }
+ var year = parseInt(parts[0], 10);
+ var month = parseInt(parts[1], 10);
+ var day = parseInt(parts[2], 10);
+
+ if (month < 1 || year < 1 || day < 1) {
+ return null;
+ }
+ return new Date(year, (month - 1), day);
+ }
+ return {
+ priority: -100, // run after default uiGridEditor directive
+ require: '?ngModel',
+ link: function (scope, element, attrs, ngModel) {
+
+ if (angular.version.minor === 2 && attrs.type && attrs.type === 'date' && ngModel) {
+
+ ngModel.$formatters.push(function (modelValue) {
+ ngModel.$setValidity(null,(!modelValue || !isNaN(modelValue.getTime())));
+ return $filter('date')(modelValue, 'yyyy-MM-dd');
+ });
+
+ ngModel.$parsers.push(function (viewValue) {
+ if (viewValue && viewValue.length > 0) {
+ var dateValue = parseDateString(viewValue);
+ ngModel.$setValidity(null, (dateValue && !isNaN(dateValue.getTime())));
+ return dateValue;
+ }
+ else {
+ ngModel.$setValidity(null, true);
+ return null;
+ }
+ });
+ }
+ }
+ };
+ }]);
+
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.edit.directive:uiGridEditDropdown
+ * @element div
+ * @restrict A
+ *
+ * @description dropdown editor for editable fields.
+ * Provides EndEdit and CancelEdit events
+ *
+ * Events that end editing:
+ * blur and enter keydown, and any left/right nav
+ *
+ * Events that cancel editing:
+ * - Esc keydown
+ *
+ */
+ module.directive('uiGridEditDropdown',
+ ['uiGridConstants', 'uiGridEditConstants', '$timeout',
+ function (uiGridConstants, uiGridEditConstants, $timeout) {
+ return {
+ require: ['?^uiGrid', '?^uiGridRenderContainer'],
+ scope: true,
+ compile: function () {
+ return {
+ pre: function ($scope, $elm, $attrs) {
+
+ },
+ post: function ($scope, $elm, $attrs, controllers) {
+ var uiGridCtrl = controllers[0];
+ var renderContainerCtrl = controllers[1];
+
+ //set focus at start of edit
+ $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function () {
+ $timeout(function(){
+ $elm[0].focus();
+ });
+
+ $elm[0].style.width = ($elm[0].parentElement.offsetWidth - 1) + 'px';
+ $elm.on('blur', function (evt) {
+ $scope.stopEdit(evt);
+ });
+ });
+
+
+ $scope.stopEdit = function (evt) {
+ // no need to validate a dropdown - invalid values shouldn't be
+ // available in the list
+ $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
+ };
+
+ $elm.on('keydown', function (evt) {
+ switch (evt.keyCode) {
+ case uiGridConstants.keymap.ESC:
+ evt.stopPropagation();
+ $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT);
+ break;
+ }
+ if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
+ evt.uiGridTargetRenderContainerId = renderContainerCtrl.containerId;
+ if (uiGridCtrl.cellNav.handleKeyDown(evt) !== null) {
+ $scope.stopEdit(evt);
+ }
+ }
+ else {
+ //handle enter and tab for editing not using cellNav
+ switch (evt.keyCode) {
+ case uiGridConstants.keymap.ENTER: // Enter (Leave Field)
+ case uiGridConstants.keymap.TAB:
+ evt.stopPropagation();
+ evt.preventDefault();
+ $scope.stopEdit(evt);
+ break;
+ }
+ }
+ return true;
+ });
+
+ $scope.$on('$destroy', function unbindEvents() {
+ // unbind jquery events to prevent memory leaks
+ $elm.off();
+ });
+ }
+ };
+ }
+ };
+ }]);
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.edit.directive:uiGridEditFileChooser
+ * @element div
+ * @restrict A
+ *
+ * @description input editor directive for editable fields.
+ * Provides EndEdit and CancelEdit events
+ *
+ * Events that end editing:
+ * blur and enter keydown
+ *
+ * Events that cancel editing:
+ * - Esc keydown
+ *
+ */
+ module.directive('uiGridEditFileChooser',
+ ['gridUtil', 'uiGridConstants', 'uiGridEditConstants',
+ function (gridUtil, uiGridConstants, uiGridEditConstants) {
+ return {
+ scope: true,
+ require: ['?^uiGrid', '?^uiGridRenderContainer'],
+ compile: function () {
+ return {
+ pre: function ($scope, $elm, $attrs) {
+
+ },
+ post: function ($scope, $elm) {
+ function handleFileSelect(event) {
+ var target = event.srcElement || event.target;
+
+ if (target && target.files && target.files.length > 0) {
+ /**
+ * @ngdoc property
+ * @name editFileChooserCallback
+ * @propertyOf ui.grid.edit.api:ColumnDef
+ * @description A function that should be called when any files have been chosen
+ * by the user. You should use this to process the files appropriately for your
+ * application.
+ *
+ * It passes the gridCol, the gridRow (from which you can get gridRow.entity),
+ * and the files. The files are in the format as returned from the file chooser,
+ * an array of files, with each having useful information such as:
+ * - `files[0].lastModifiedDate`
+ * - `files[0].name`
+ * - `files[0].size` (appears to be in bytes)
+ * - `files[0].type` (MIME type by the looks)
+ *
+ * Typically you would do something with these files - most commonly you would
+ * use the filename or read the file itself in. The example function does both.
+ *
+ * @example
+ *
+ * editFileChooserCallBack: function(gridRow, gridCol, files ){
+ * // ignore all but the first file, it can only choose one anyway
+ * // set the filename into this column
+ * gridRow.entity.filename = file[0].name;
+ *
+ * // read the file and set it into a hidden column, which we may do stuff with later
+ * var setFile = function(fileContent){
+ * gridRow.entity.file = fileContent.currentTarget.result;
+ * };
+ * var reader = new FileReader();
+ * reader.onload = setFile;
+ * reader.readAsText( files[0] );
+ * }
+ *
+ */
+ if ( typeof($scope.col.colDef.editFileChooserCallback) === 'function' ) {
+ $scope.col.colDef.editFileChooserCallback($scope.row, $scope.col, target.files);
+ } else {
+ gridUtil.logError('You need to set colDef.editFileChooserCallback to use the file chooser');
+ }
+
+ target.form.reset();
+ $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
+ } else {
+ $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT);
+ }
+ $elm[0].removeEventListener('change', handleFileSelect, false);
+ }
+
+ $elm[0].addEventListener('change', handleFileSelect, false);
+
+ $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function () {
+ $elm[0].focus();
+ $elm[0].select();
+
+ $elm.on('blur', function () {
+ $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
+ $elm.off();
+ });
+ });
+ }
+ };
+ }
+ };
+ }]);
+})();
diff --git a/release/4.4.11/ui-grid.edit.min.js b/release/4.4.11/ui-grid.edit.min.js
new file mode 100644
index 000000000..9521a3326
--- /dev/null
+++ b/release/4.4.11/ui-grid.edit.min.js
@@ -0,0 +1,7 @@
+/*!
+ * ui-grid - v4.4.11 - 2018-05-16
+ * Copyright (c) 2018 ; License: MIT
+ */
+
+
+!function(){"use strict";var e=angular.module("ui.grid.edit",["ui.grid"]);e.constant("uiGridEditConstants",{EDITABLE_CELL_TEMPLATE:/EDITABLE_CELL_TEMPLATE/g,EDITABLE_CELL_DIRECTIVE:/editable_cell_directive/g,events:{BEGIN_CELL_EDIT:"uiGridEventBeginCellEdit",END_CELL_EDIT:"uiGridEventEndCellEdit",CANCEL_CELL_EDIT:"uiGridEventCancelCellEdit"}}),e.service("uiGridEditService",["$q","uiGridConstants","gridUtil",function(o,i,l){var t={initializeGrid:function(e){t.defaultGridOptions(e.options),e.registerColumnBuilder(t.editColumnBuilder),e.edit={};e.api.registerEventsFromObject({edit:{afterCellEdit:function(e,i,t,n){},beginCellEdit:function(e,i,t){},cancelCellEdit:function(e,i){}}})},defaultGridOptions:function(e){e.cellEditableCondition=void 0===e.cellEditableCondition||e.cellEditableCondition,e.enableCellEditOnFocus=void 0!==e.enableCellEditOnFocus&&e.enableCellEditOnFocus},editColumnBuilder:function(i,t,e){var n=[];return i.enableCellEdit=void 0===i.enableCellEdit?void 0===e.enableCellEdit?"object"!==i.type:e.enableCellEdit:i.enableCellEdit,i.cellEditableCondition=void 0===i.cellEditableCondition?e.cellEditableCondition:i.cellEditableCondition,i.enableCellEdit&&(i.editableCellTemplate=i.editableCellTemplate||e.editableCellTemplate||"ui-grid/cellEditor",n.push(l.getTemplate(i.editableCellTemplate).then(function(e){t.editableCellTemplate=e},function(e){throw new Error("Couldn't fetch/use colDef.editableCellTemplate '"+i.editableCellTemplate+"'")}))),i.enableCellEditOnFocus=void 0===i.enableCellEditOnFocus?e.enableCellEditOnFocus:i.enableCellEditOnFocus,o.all(n)},isStartEditKey:function(e){return!(e.metaKey||e.keyCode===i.keymap.ESC||e.keyCode===i.keymap.SHIFT||e.keyCode===i.keymap.CTRL||e.keyCode===i.keymap.ALT||e.keyCode===i.keymap.WIN||e.keyCode===i.keymap.CAPSLOCK||e.keyCode===i.keymap.LEFT||e.keyCode===i.keymap.TAB&&e.shiftKey||e.keyCode===i.keymap.RIGHT||e.keyCode===i.keymap.TAB||e.keyCode===i.keymap.UP||e.keyCode===i.keymap.ENTER&&e.shiftKey||e.keyCode===i.keymap.DOWN||e.keyCode===i.keymap.ENTER)}};return t}]),e.directive("uiGridEdit",["gridUtil","uiGridEditService",function(e,o){return{replace:!0,priority:0,require:"^uiGrid",scope:!1,compile:function(){return{pre:function(e,i,t,n){o.initializeGrid(n.grid)},post:function(e,i,t,n){}}}}}]),e.directive("uiGridViewport",["uiGridEditConstants",function(l){return{replace:!0,priority:-99998,require:["^uiGrid","^uiGridRenderContainer"],scope:!1,compile:function(){return{post:function(e,i,t,n){var o=n[0];o.grid.api.edit&&o.grid.api.cellNav&&("body"===n[1].containerId&&(e.$on(l.events.CANCEL_CELL_EDIT,function(){o.focus()}),e.$on(l.events.END_CELL_EDIT,function(){o.focus()})))}}}}}]),e.directive("uiGridCell",["$compile","$injector","$timeout","uiGridConstants","uiGridEditConstants","gridUtil","$parse","uiGridEditService","$rootScope","$q",function(L,e,k,h,T,w,_,f,G,I){var $=500;if(e.has("uiGridCellNavService"))e.get("uiGridCellNavService");return{priority:-100,restrict:"A",scope:!1,require:"?^uiGrid",link:function(E,p,e,n){var C,v,y,i,g,D=!1;if(E.col.colDef.enableCellEdit){var t=function(){},o=function(){},l=function(){E.col.colDef.enableCellEdit&&!1!==E.row.enableCellEdit?E.beginEditEventsWired||d():E.beginEditEventsWired&&m()};l();var r=E.$watch("row",function(e,i){e!==i&&l()});E.$on("$destroy",function(){r(),p.off()})}function d(){p.on("dblclick",s),p.on("touchstart",c),n&&n.grid.api.cellNav&&(o=n.grid.api.cellNav.on.viewPortKeyDown(E,function(e,i){null!==i&&(i.row!==E.row||i.col!==E.col||E.col.colDef.enableCellEditOnFocus||u(e))}),t=n.grid.api.cellNav.on.navigate(E,function(e,i,t){E.col.colDef.enableCellEditOnFocus&&(e.row!==E.row||e.col!==E.col||null!==t&&(!t||"click"!==t.type&&"keydown"!==t.type)||k(function(){s(t)}))})),E.beginEditEventsWired=!0}function c(e){void 0!==e.originalEvent&&void 0!==e.originalEvent&&(e=e.originalEvent),p.on("touchend",a),(i=k(function(){},$)).then(function(){setTimeout(s,0),p.off("touchend",a)})}function a(e){k.cancel(i),p.off("touchend",a)}function m(){p.off("dblclick",s),p.off("keydown",u),p.off("touchstart",c),t(),o(),E.beginEditEventsWired=!1}function u(e){f.isStartEditKey(e)&&s(e)}function s(e){E.grid.api.core.scrollToIfNecessary(E.row,E.col).then(function(){!function(e){if(D)return;if(i=E.col,t=E.row,n=e,t.isSaving||(angular.isFunction(i.colDef.cellEditableCondition)?!i.colDef.cellEditableCondition(E,n):!i.colDef.cellEditableCondition))return;var i,t,n;var o=E.row.getQualifiedColField(E.col);E.col.colDef.editModelField&&(o=w.preEval("row.entity."+E.col.colDef.editModelField));y=_(o),v=y(E),C=(C=(C=E.col.editableCellTemplate).replace(h.MODEL_COL_FIELD,o)).replace(h.COL_FIELD,"grid.getCellValue(row, col)");var l=E.col.colDef.editDropdownFilter?"|"+E.col.colDef.editDropdownFilter:"";C=C.replace(h.CUSTOM_FILTERS,l);var r="text";switch(E.col.colDef.type){case"boolean":r="checkbox";break;case"number":r="number";break;case"date":r="date"}C=C.replace("INPUT_TYPE",r);var d=E.col.colDef.editDropdownOptionsFunction;if(d)I.when(d(E.row.entity,E.col.colDef)).then(function(e){E.editDropdownOptionsArray=e});else{var c=E.col.colDef.editDropdownRowEntityOptionsArrayPath;E.editDropdownOptionsArray=c?function(e,i){var t=(i=(i=i.replace(/\[(\w+)\]/g,".$1")).replace(/^\./,"")).split(".");for(;t.length;){var n=t.shift();if(!(n in e))return;e=e[n]}return e}(E.row.entity,c):E.col.colDef.editDropdownOptionsArray}E.editDropdownIdLabel=E.col.colDef.editDropdownIdLabel?E.col.colDef.editDropdownIdLabel:"id",E.editDropdownValueLabel=E.col.colDef.editDropdownValueLabel?E.col.colDef.editDropdownValueLabel:"value";var a=function(){D=!0,m();var e=angular.element(C);p.append(e),g=E.$new(),L(e)(g);var i=angular.element(p.children()[0]);i.addClass("ui-grid-cell-contents-hidden")};G.$$phase?a():E.$apply(a);var u=E.col.grid.api.core.on.scrollBegin(E,function(){E.grid.disableScrolling||(b(),E.grid.api.edit.raise.afterCellEdit(E.row.entity,E.col.colDef,y(E),v),u(),s(),f())}),s=E.$on(T.events.END_CELL_EDIT,function(){b(),E.grid.api.edit.raise.afterCellEdit(E.row.entity,E.col.colDef,y(E),v),s(),u(),f()}),f=E.$on(T.events.CANCEL_CELL_EDIT,function(){!function(){if(E.grid.disableScrolling=!1,!D)return;y.assign(E,v),E.$apply(),E.grid.api.edit.raise.cancelCellEdit(E.row.entity,E.col.colDef),b()}(),f(),u(),s()});E.$broadcast(T.events.BEGIN_CELL_EDIT,e),k(function(){E.grid.api.edit.raise.beginCellEdit(E.row.entity,E.col.colDef,e)})}(e)})}function b(){if(E.grid.disableScrolling=!1,D){n&&n.grid.api.cellNav&&n.focus();var e=angular.element(p.children()[0]);g.$destroy();for(var i=p.children(),t=1;t
Defaults to true, if the directive is used.
+ *
Set to false either by setting this attribute or passing false to the directive.
+ */
+ //default option to true unless it was explicitly set to false
+ if (grid.options.enableEmptyGridBaseLayer !== false) {
+ grid.options.enableEmptyGridBaseLayer = !disableEmptyBaseLayer;
+ }
+ },
+
+ setNumberOfEmptyRows: function(viewportHeight, grid) {
+ var rowHeight = grid.options.rowHeight,
+ rows = Math.ceil(viewportHeight / rowHeight);
+ if (rows > 0) {
+ grid.baseLayer.emptyRows = [];
+ for (var i = 0; i < rows; i++) {
+ grid.baseLayer.emptyRows.push({});
+ }
+ }
+ }
+ };
+ return service;
+ }]);
+
+ /**
+ * @ngdoc object
+ * @name ui.grid.emptyBaseLayer.directive:uiGridEmptyBaseLayer
+ * @description Shows empty rows in the background of the ui-grid, these span
+ * the full height of the ui-grid, so that there won't be blank space below the shown rows.
+ * @example
+ *
+ *
+ *
+ * Or you can enable/disable it dynamically by passing in true or false. It doesn't
+ * the value, so it would only be set on initial render.
+ *
+ *
+ *
+ */
+ module.directive('uiGridEmptyBaseLayer', ['gridUtil', 'uiGridBaseLayerService',
+ '$parse',
+ function (gridUtil, uiGridBaseLayerService, $parse) {
+ return {
+ require: '^uiGrid',
+ scope: false,
+ compile: function ($elm, $attrs) {
+ return {
+ pre: function ($scope, $elm, $attrs, uiGridCtrl) {
+ var disableEmptyBaseLayer = $parse($attrs.uiGridEmptyBaseLayer)($scope) === false;
+ uiGridBaseLayerService.initializeGrid(uiGridCtrl.grid, disableEmptyBaseLayer);
+ },
+ post: function ($scope, $elm, $attrs, uiGridCtrl) {
+ if (!uiGridCtrl.grid.options.enableEmptyGridBaseLayer) {
+ return;
+ }
+
+ var renderBodyContainer = uiGridCtrl.grid.renderContainers.body,
+ viewportHeight = renderBodyContainer.getViewportHeight();
+
+ function heightHasChanged() {
+ var newViewPortHeight = renderBodyContainer.getViewportHeight();
+
+ if (newViewPortHeight !== viewportHeight) {
+ viewportHeight = newViewPortHeight;
+ return true;
+ }
+ return false;
+ }
+
+ function getEmptyBaseLayerCss(viewportHeight) {
+ // Set ui-grid-empty-base-layer height
+ return '.grid' + uiGridCtrl.grid.id +
+ ' .ui-grid-render-container ' +
+ '.ui-grid-empty-base-layer-container.ui-grid-canvas ' +
+ '{ height: ' + viewportHeight + 'px; }';
+ }
+
+ uiGridCtrl.grid.registerStyleComputation({
+ func: function() {
+ if (heightHasChanged()) {
+ uiGridBaseLayerService.setNumberOfEmptyRows(viewportHeight, uiGridCtrl.grid);
+ }
+ return getEmptyBaseLayerCss(viewportHeight);
+ }
+ });
+ }
+ };
+ }
+ };
+ }]);
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.emptyBaseLayer.directive:uiGridViewport
+ * @description stacks on the uiGridViewport directive to append the empty grid base layer html elements to the
+ * default gridRow template
+ */
+ module.directive('uiGridViewport',
+ ['$compile', 'gridUtil', '$templateCache',
+ function ($compile, gridUtil, $templateCache) {
+ return {
+ priority: -200,
+ scope: false,
+ compile: function ($elm, $attrs) {
+ var emptyBaseLayerContainer = $templateCache.get('ui-grid/emptyBaseLayerContainer');
+ $elm.prepend(emptyBaseLayerContainer);
+ return {
+ pre: function ($scope, $elm, $attrs, controllers) {
+ },
+ post: function ($scope, $elm, $attrs, controllers) {
+ }
+ };
+ }
+ };
+ }]);
+
+})();
diff --git a/release/4.4.11/ui-grid.empty-base-layer.min.js b/release/4.4.11/ui-grid.empty-base-layer.min.js
new file mode 100644
index 000000000..b2fd2cbbc
--- /dev/null
+++ b/release/4.4.11/ui-grid.empty-base-layer.min.js
@@ -0,0 +1,7 @@
+/*!
+ * ui-grid - v4.4.11 - 2018-05-16
+ * Copyright (c) 2018 ; License: MIT
+ */
+
+
+!function(){"use strict";var e=angular.module("ui.grid.emptyBaseLayer",["ui.grid"]);e.service("uiGridBaseLayerService",["gridUtil","$compile",function(e,i){return{initializeGrid:function(e,i){!(e.baseLayer={emptyRows:[]})!==e.options.enableEmptyGridBaseLayer&&(e.options.enableEmptyGridBaseLayer=!i)},setNumberOfEmptyRows:function(e,i){var r=i.options.rowHeight,t=Math.ceil(e/r);if(0
z#6o_lfFK;C!vw+sMGFH`_^!0{_5d%Edf}#4p%!lH`dUQecm5uYwL1U0ODp^rLV*U}
zT3vtV9qJ}q7k`dDx>_s%>(#NKkD}Ub&bg&YIzY(9D+4YZZ8%iADtROMsN(lj7Jd?P
zx%|enM&T!`s#c3P!r~7@U=~h<4aNJc*T?<5s*;jy%FJ-SUPmS#W=*VzCD
+ * $scope.gridOptions = {
+ * enableExpandable: false
+ * }
+ *
+ */
+ grid.options.enableExpandable = grid.options.enableExpandable !== false;
+
+ /**
+ * @ngdoc object
+ * @name showExpandAllButton
+ * @propertyOf ui.grid.expandable.api:GridOptions
+ * @description Whether or not to display the expand all button, allows you to hide expand all button on specific grids
+ * within your application, or in specific modes on _this_ grid. Defaults to true.
+ * @example
+ *
+ * $scope.gridOptions = {
+ * showExpandAllButton: false
+ * }
+ *
+ */
+ grid.options.showExpandAllButton = grid.options.showExpandAllButton !== false;
+
+ /**
+ * @ngdoc object
+ * @name expandableRowHeight
+ * @propertyOf ui.grid.expandable.api:GridOptions
+ * @description Height in pixels of the expanded subgrid. Defaults to
+ * 150
+ * @example
+ *
+ * $scope.gridOptions = {
+ * expandableRowHeight: 150
+ * }
+ *
+ */
+ grid.options.expandableRowHeight = grid.options.expandableRowHeight || 150;
+
+ /**
+ * @ngdoc object
+ * @name expandableRowHeaderWidth
+ * @propertyOf ui.grid.expandable.api:GridOptions
+ * @description Width in pixels of the expandable column. Defaults to 40
+ * @example
+ *
+ * $scope.gridOptions = {
+ * expandableRowHeaderWidth: 40
+ * }
+ *
+ */
+ grid.options.expandableRowHeaderWidth = grid.options.expandableRowHeaderWidth || 40;
+
+ /**
+ * @ngdoc object
+ * @name expandableRowTemplate
+ * @propertyOf ui.grid.expandable.api:GridOptions
+ * @description Mandatory. The template for your expanded row
+ * @example
+ *
+ * $scope.gridOptions = {
+ * expandableRowTemplate: 'expandableRowTemplate.html'
+ * }
+ *
+ */
+ if ( grid.options.enableExpandable && !grid.options.expandableRowTemplate ){
+ gridUtil.logError( 'You have not set the expandableRowTemplate, disabling expandable module' );
+ grid.options.enableExpandable = false;
+ }
+
+ /**
+ * @ngdoc object
+ * @name ui.grid.expandable.api:PublicApi
+ *
+ * @description Public Api for expandable feature
+ */
+ /**
+ * @ngdoc object
+ * @name ui.grid.expandable.api:GridRow
+ *
+ * @description Additional properties added to GridRow when using the expandable module
+ */
+ /**
+ * @ngdoc object
+ * @name ui.grid.expandable.api:GridOptions
+ *
+ * @description Options for configuring the expandable feature, these are available to be
+ * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
+ */
+ var publicApi = {
+ events: {
+ expandable: {
+ /**
+ * @ngdoc event
+ * @name rowExpandedBeforeStateChanged
+ * @eventOf ui.grid.expandable.api:PublicApi
+ * @description raised when row is expanding or collapsing
+ *
+ * gridApi.expandable.on.rowExpandedBeforeStateChanged(scope,function(row){})
+ *
+ * @param {scope} scope the application scope
+ * @param {GridRow} row the row that was expanded
+ */
+ rowExpandedBeforeStateChanged: function(scope, row){
+ },
+ /**
+ * @ngdoc event
+ * @name rowExpandedStateChanged
+ * @eventOf ui.grid.expandable.api:PublicApi
+ * @description raised when row expanded or collapsed
+ *
+ * gridApi.expandable.on.rowExpandedStateChanged(scope,function(row){})
+ *
+ * @param {scope} scope the application scope
+ * @param {GridRow} row the row that was expanded
+ */
+ rowExpandedStateChanged: function (scope, row) {
+ }
+ }
+ },
+
+ methods: {
+ expandable: {
+ /**
+ * @ngdoc method
+ * @name toggleRowExpansion
+ * @methodOf ui.grid.expandable.api:PublicApi
+ * @description Toggle a specific row
+ *
+ * gridApi.expandable.toggleRowExpansion(rowEntity);
+ *
+ * @param {object} rowEntity the data entity for the row you want to expand
+ */
+ toggleRowExpansion: function (rowEntity) {
+ var row = grid.getRow(rowEntity);
+ if (row !== null) {
+ service.toggleRowExpansion(grid, row);
+ }
+ },
+
+ /**
+ * @ngdoc method
+ * @name expandAllRows
+ * @methodOf ui.grid.expandable.api:PublicApi
+ * @description Expand all subgrids.
+ *
+ * gridApi.expandable.expandAllRows();
+ *
+ */
+ expandAllRows: function() {
+ service.expandAllRows(grid);
+ },
+
+ /**
+ * @ngdoc method
+ * @name collapseAllRows
+ * @methodOf ui.grid.expandable.api:PublicApi
+ * @description Collapse all subgrids.
+ *
+ * gridApi.expandable.collapseAllRows();
+ *
+ */
+ collapseAllRows: function() {
+ service.collapseAllRows(grid);
+ },
+
+ /**
+ * @ngdoc method
+ * @name toggleAllRows
+ * @methodOf ui.grid.expandable.api:PublicApi
+ * @description Toggle all subgrids.
+ *
+ * gridApi.expandable.toggleAllRows();
+ *
+ */
+ toggleAllRows: function() {
+ service.toggleAllRows(grid);
+ },
+ /**
+ * @ngdoc function
+ * @name expandRow
+ * @methodOf ui.grid.expandable.api:PublicApi
+ * @description Expand the data row
+ * @param {object} rowEntity gridOptions.data[] array instance
+ */
+ expandRow: function (rowEntity) {
+ var row = grid.getRow(rowEntity);
+ if (row !== null && !row.isExpanded) {
+ service.toggleRowExpansion(grid, row);
+ }
+ },
+ /**
+ * @ngdoc function
+ * @name collapseRow
+ * @methodOf ui.grid.expandable.api:PublicApi
+ * @description Collapse the data row
+ * @param {object} rowEntity gridOptions.data[] array instance
+ */
+ collapseRow: function (rowEntity) {
+ var row = grid.getRow(rowEntity);
+ if (row !== null && row.isExpanded) {
+ service.toggleRowExpansion(grid, row);
+ }
+ },
+ /**
+ * @ngdoc function
+ * @name getExpandedRows
+ * @methodOf ui.grid.expandable.api:PublicApi
+ * @description returns all expandedRow's entity references
+ */
+ getExpandedRows: function () {
+ return service.getExpandedRows(grid).map(function (gridRow) {
+ return gridRow.entity;
+ });
+ }
+ }
+ }
+ };
+ grid.api.registerEventsFromObject(publicApi.events);
+ grid.api.registerMethodsFromObject(publicApi.methods);
+ },
+
+ toggleRowExpansion: function (grid, row) {
+ // trigger the "before change" event. Can change row height dynamically this way.
+ grid.api.expandable.raise.rowExpandedBeforeStateChanged(row);
+ /**
+ * @ngdoc object
+ * @name isExpanded
+ * @propertyOf ui.grid.expandable.api:GridRow
+ * @description Whether or not the row is currently expanded.
+ * @example
+ *
+ * $scope.api.expandable.on.rowExpandedStateChanged($scope, function (row) {
+ * if (row.isExpanded) {
+ * //...
+ * }
+ * });
+ *
+ */
+ row.isExpanded = !row.isExpanded;
+ if (angular.isUndefined(row.expandedRowHeight)){
+ row.expandedRowHeight = grid.options.expandableRowHeight;
+ }
+
+ if (row.isExpanded) {
+ row.height = row.grid.options.rowHeight + row.expandedRowHeight;
+ grid.expandable.expandedAll = service.getExpandedRows(grid).length === grid.rows.length;
+ } else {
+ row.height = row.grid.options.rowHeight;
+ grid.expandable.expandedAll = false;
+ }
+ grid.api.expandable.raise.rowExpandedStateChanged(row);
+ },
+
+ expandAllRows: function(grid) {
+ grid.renderContainers.body.visibleRowCache.forEach( function(row) {
+ if (!row.isExpanded && !(row.entity.subGridOptions && row.entity.subGridOptions.disableRowExpandable)) {
+ service.toggleRowExpansion(grid, row);
+ }
+ });
+ grid.expandable.expandedAll = true;
+ grid.queueGridRefresh();
+ },
+
+ collapseAllRows: function(grid) {
+ grid.renderContainers.body.visibleRowCache.forEach( function(row) {
+ if (row.isExpanded) {
+ service.toggleRowExpansion(grid, row);
+ }
+ });
+ grid.expandable.expandedAll = false;
+ grid.queueGridRefresh();
+ },
+
+ toggleAllRows: function(grid) {
+ if (grid.expandable.expandedAll) {
+ service.collapseAllRows(grid);
+ }
+ else {
+ service.expandAllRows(grid);
+ }
+ },
+
+ getExpandedRows: function (grid) {
+ return grid.rows.filter(function (row) {
+ return row.isExpanded;
+ });
+ }
+ };
+ return service;
+ }]);
+
+ /**
+ * @ngdoc object
+ * @name enableExpandableRowHeader
+ * @propertyOf ui.grid.expandable.api:GridOptions
+ * @description Show a rowHeader to provide the expandable buttons. If set to false then implies
+ * you're going to use a custom method for expanding and collapsing the subgrids. Defaults to true.
+ * @example
+ *
+ * $scope.gridOptions = {
+ * enableExpandableRowHeader: false
+ * }
+ *
+ */
+ module.directive('uiGridExpandable', ['uiGridExpandableService', '$templateCache',
+ function (uiGridExpandableService, $templateCache) {
+ return {
+ replace: true,
+ priority: 0,
+ require: '^uiGrid',
+ scope: false,
+ compile: function () {
+ return {
+ pre: function ($scope, $elm, $attrs, uiGridCtrl) {
+ uiGridExpandableService.initializeGrid(uiGridCtrl.grid);
+
+ if (!uiGridCtrl.grid.options.enableExpandable) {
+ return;
+ }
+
+ if (uiGridCtrl.grid.options.enableExpandableRowHeader !== false ) {
+ var expandableRowHeaderColDef = {
+ name: 'expandableButtons',
+ displayName: '',
+ exporterSuppressExport: true,
+ enableColumnResizing: false,
+ enableColumnMenu: false,
+ width: uiGridCtrl.grid.options.expandableRowHeaderWidth || 40
+ };
+ expandableRowHeaderColDef.cellTemplate = $templateCache.get('ui-grid/expandableRowHeader');
+ expandableRowHeaderColDef.headerCellTemplate = $templateCache.get('ui-grid/expandableTopRowHeader');
+ uiGridCtrl.grid.addRowHeaderColumn(expandableRowHeaderColDef, -90);
+ }
+
+ },
+ post: function ($scope, $elm, $attrs, uiGridCtrl) {
+ }
+ };
+ }
+ };
+ }]);
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.expandable.directive:uiGrid
+ * @description stacks on the uiGrid directive to register child grid with parent row when child is created
+ */
+ module.directive('uiGrid', ['uiGridExpandableService', '$templateCache',
+ function (uiGridExpandableService, $templateCache) {
+ return {
+ replace: true,
+ priority: 599,
+ require: '^uiGrid',
+ scope: false,
+ compile: function () {
+ return {
+ pre: function ($scope, $elm, $attrs, uiGridCtrl) {
+
+ uiGridCtrl.grid.api.core.on.renderingComplete($scope, function() {
+ //if a parent grid row is on the scope, then add the parentRow property to this childGrid
+ if ($scope.row && $scope.row.grid && $scope.row.grid.options && $scope.row.grid.options.enableExpandable) {
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.expandable.class:Grid
+ * @description Additional Grid properties added by expandable module
+ */
+
+ /**
+ * @ngdoc object
+ * @name parentRow
+ * @propertyOf ui.grid.expandable.class:Grid
+ * @description reference to the expanded parent row that owns this grid
+ */
+ uiGridCtrl.grid.parentRow = $scope.row;
+
+ //todo: adjust height on parent row when child grid height changes. we need some sort of gridHeightChanged event
+ // uiGridCtrl.grid.core.on.canvasHeightChanged($scope, function(oldHeight, newHeight) {
+ // uiGridCtrl.grid.parentRow = newHeight;
+ // });
+ }
+
+ });
+ },
+ post: function ($scope, $elm, $attrs, uiGridCtrl) {
+
+ }
+ };
+ }
+ };
+ }]);
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.expandable.directive:uiGridExpandableRow
+ * @description directive to render the expandable row template
+ */
+ module.directive('uiGridExpandableRow',
+ ['uiGridExpandableService', '$timeout', '$compile', 'uiGridConstants','gridUtil','$interval', '$log',
+ function (uiGridExpandableService, $timeout, $compile, uiGridConstants, gridUtil, $interval, $log) {
+
+ return {
+ replace: false,
+ priority: 0,
+ scope: false,
+
+ compile: function () {
+ return {
+ pre: function ($scope, $elm, $attrs, uiGridCtrl) {
+ gridUtil.getTemplate($scope.grid.options.expandableRowTemplate).then(
+ function (template) {
+ if ($scope.grid.options.expandableRowScope) {
+ /**
+ * @ngdoc object
+ * @name expandableRowScope
+ * @propertyOf ui.grid.expandable.api:GridOptions
+ * @description Variables of object expandableScope will be available in the scope of the expanded subgrid
+ * @example
+ *
+ * $scope.gridOptions = {
+ * expandableRowScope: expandableScope
+ * }
+ *
+ */
+ var expandableRowScope = $scope.grid.options.expandableRowScope;
+ for (var property in expandableRowScope) {
+ if (expandableRowScope.hasOwnProperty(property)) {
+ $scope[property] = expandableRowScope[property];
+ }
+ }
+ }
+ var expandedRowElement = angular.element(template);
+ $elm.append(expandedRowElement);
+ expandedRowElement = $compile(expandedRowElement)($scope);
+ $scope.row.expandedRendered = true;
+ });
+ },
+
+ post: function ($scope, $elm, $attrs, uiGridCtrl) {
+ $scope.$on('$destroy', function() {
+ $scope.row.expandedRendered = false;
+ });
+ }
+ };
+ }
+ };
+ }]);
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.expandable.directive:uiGridRow
+ * @description stacks on the uiGridRow directive to add support for expandable rows
+ */
+ module.directive('uiGridRow',
+ ['$compile', 'gridUtil', '$templateCache',
+ function ($compile, gridUtil, $templateCache) {
+ return {
+ priority: -200,
+ scope: false,
+ compile: function ($elm, $attrs) {
+ return {
+ pre: function ($scope, $elm, $attrs, controllers) {
+
+ if (!$scope.grid.options.enableExpandable) {
+ return;
+ }
+
+ $scope.expandableRow = {};
+
+ $scope.expandableRow.shouldRenderExpand = function () {
+ var ret = $scope.colContainer.name === 'body' && $scope.grid.options.enableExpandable !== false && $scope.row.isExpanded && (!$scope.grid.isScrollingVertically || $scope.row.expandedRendered);
+ return ret;
+ };
+
+ $scope.expandableRow.shouldRenderFiller = function () {
+ var ret = $scope.row.isExpanded && ( $scope.colContainer.name !== 'body' || ($scope.grid.isScrollingVertically && !$scope.row.expandedRendered));
+ return ret;
+ };
+
+ /*
+ * Commented out @PaulL1. This has no purpose that I can see, and causes #2964. If this code needs to be reinstated for some
+ * reason it needs to use drawnWidth, not width, and needs to check column visibility. It should really use render container
+ * visible column cache also instead of checking column.renderContainer.
+ function updateRowContainerWidth() {
+ var grid = $scope.grid;
+ var colWidth = 0;
+ grid.columns.forEach( function (column) {
+ if (column.renderContainer === 'left') {
+ colWidth += column.width;
+ }
+ });
+ colWidth = Math.floor(colWidth);
+ return '.grid' + grid.id + ' .ui-grid-pinned-container-' + $scope.colContainer.name + ', .grid' + grid.id +
+ ' .ui-grid-pinned-container-' + $scope.colContainer.name + ' .ui-grid-render-container-' + $scope.colContainer.name +
+ ' .ui-grid-viewport .ui-grid-canvas .ui-grid-row { width: ' + colWidth + 'px; }';
+ }
+
+ if ($scope.colContainer.name === 'left') {
+ $scope.grid.registerStyleComputation({
+ priority: 15,
+ func: updateRowContainerWidth
+ });
+ }*/
+
+ },
+ post: function ($scope, $elm, $attrs, controllers) {
+ }
+ };
+ }
+ };
+ }]);
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.expandable.directive:uiGridViewport
+ * @description stacks on the uiGridViewport directive to append the expandable row html elements to the
+ * default gridRow template
+ */
+ module.directive('uiGridViewport',
+ ['$compile', 'gridUtil', '$templateCache',
+ function ($compile, gridUtil, $templateCache) {
+ return {
+ priority: -200,
+ scope: false,
+ compile: function ($elm, $attrs) {
+
+ //todo: this adds ng-if watchers to each row even if the grid is not using expandable directive
+ // or options.enableExpandable == false
+ // The alternative is to compile the template and append to each row in a uiGridRow directive
+
+ var rowRepeatDiv = angular.element($elm.children().children()[0]);
+ var expandedRowFillerElement = $templateCache.get('ui-grid/expandableScrollFiller');
+ var expandedRowElement = $templateCache.get('ui-grid/expandableRow');
+ rowRepeatDiv.append(expandedRowElement);
+ rowRepeatDiv.append(expandedRowFillerElement);
+ return {
+ pre: function ($scope, $elm, $attrs, controllers) {
+ },
+ post: function ($scope, $elm, $attrs, controllers) {
+ }
+ };
+ }
+ };
+ }]);
+
+})();
diff --git a/release/4.4.11/ui-grid.expandable.min.js b/release/4.4.11/ui-grid.expandable.min.js
new file mode 100644
index 000000000..7bceaef08
--- /dev/null
+++ b/release/4.4.11/ui-grid.expandable.min.js
@@ -0,0 +1,7 @@
+/*!
+ * ui-grid - v4.4.11 - 2018-05-16
+ * Copyright (c) 2018 ; License: MIT
+ */
+
+
+!function(){"use strict";var e=angular.module("ui.grid.expandable",["ui.grid"]);e.service("uiGridExpandableService",["gridUtil","$compile",function(n,e){var i={initializeGrid:function(o){o.expandable={},o.expandable.expandedAll=!1,o.options.enableExpandable=!1!==o.options.enableExpandable,o.options.showExpandAllButton=!1!==o.options.showExpandAllButton,o.options.expandableRowHeight=o.options.expandableRowHeight||150,o.options.expandableRowHeaderWidth=o.options.expandableRowHeaderWidth||40,o.options.enableExpandable&&!o.options.expandableRowTemplate&&(n.logError("You have not set the expandableRowTemplate, disabling expandable module"),o.options.enableExpandable=!1);var e={events:{expandable:{rowExpandedBeforeStateChanged:function(e,n){},rowExpandedStateChanged:function(e,n){}}},methods:{expandable:{toggleRowExpansion:function(e){var n=o.getRow(e);null!==n&&i.toggleRowExpansion(o,n)},expandAllRows:function(){i.expandAllRows(o)},collapseAllRows:function(){i.collapseAllRows(o)},toggleAllRows:function(){i.toggleAllRows(o)},expandRow:function(e){var n=o.getRow(e);null===n||n.isExpanded||i.toggleRowExpansion(o,n)},collapseRow:function(e){var n=o.getRow(e);null!==n&&n.isExpanded&&i.toggleRowExpansion(o,n)},getExpandedRows:function(){return i.getExpandedRows(o).map(function(e){return e.entity})}}}};o.api.registerEventsFromObject(e.events),o.api.registerMethodsFromObject(e.methods)},toggleRowExpansion:function(e,n){e.api.expandable.raise.rowExpandedBeforeStateChanged(n),n.isExpanded=!n.isExpanded,angular.isUndefined(n.expandedRowHeight)&&(n.expandedRowHeight=e.options.expandableRowHeight),n.isExpanded?(n.height=n.grid.options.rowHeight+n.expandedRowHeight,e.expandable.expandedAll=i.getExpandedRows(e).length===e.rows.length):(n.height=n.grid.options.rowHeight,e.expandable.expandedAll=!1),e.api.expandable.raise.rowExpandedStateChanged(n)},expandAllRows:function(n){n.renderContainers.body.visibleRowCache.forEach(function(e){e.isExpanded||e.entity.subGridOptions&&e.entity.subGridOptions.disableRowExpandable||i.toggleRowExpansion(n,e)}),n.expandable.expandedAll=!0,n.queueGridRefresh()},collapseAllRows:function(n){n.renderContainers.body.visibleRowCache.forEach(function(e){e.isExpanded&&i.toggleRowExpansion(n,e)}),n.expandable.expandedAll=!1,n.queueGridRefresh()},toggleAllRows:function(e){e.expandable.expandedAll?i.collapseAllRows(e):i.expandAllRows(e)},getExpandedRows:function(e){return e.rows.filter(function(e){return e.isExpanded})}};return i}]),e.directive("uiGridExpandable",["uiGridExpandableService","$templateCache",function(d,t){return{replace:!0,priority:0,require:"^uiGrid",scope:!1,compile:function(){return{pre:function(e,n,o,i){if(d.initializeGrid(i.grid),i.grid.options.enableExpandable&&!1!==i.grid.options.enableExpandableRowHeader){var a={name:"expandableButtons",displayName:"",exporterSuppressExport:!0,enableColumnResizing:!1,enableColumnMenu:!1,width:i.grid.options.expandableRowHeaderWidth||40};a.cellTemplate=t.get("ui-grid/expandableRowHeader"),a.headerCellTemplate=t.get("ui-grid/expandableTopRowHeader"),i.grid.addRowHeaderColumn(a,-90)}},post:function(e,n,o,i){}}}}}]),e.directive("uiGrid",["uiGridExpandableService","$templateCache",function(e,n){return{replace:!0,priority:599,require:"^uiGrid",scope:!1,compile:function(){return{pre:function(e,n,o,i){i.grid.api.core.on.renderingComplete(e,function(){e.row&&e.row.grid&&e.row.grid.options&&e.row.grid.options.enableExpandable&&(i.grid.parentRow=e.row)})},post:function(e,n,o,i){}}}}}]),e.directive("uiGridExpandableRow",["uiGridExpandableService","$timeout","$compile","uiGridConstants","gridUtil","$interval","$log",function(e,n,t,o,i,a,d){return{replace:!1,priority:0,scope:!1,compile:function(){return{pre:function(a,d,e,n){i.getTemplate(a.grid.options.expandableRowTemplate).then(function(e){if(a.grid.options.expandableRowScope){var n=a.grid.options.expandableRowScope;for(var o in n)n.hasOwnProperty(o)&&(a[o]=n[o])}var i=angular.element(e);d.append(i),i=t(i)(a),a.row.expandedRendered=!0})},post:function(e,n,o,i){e.$on("$destroy",function(){e.row.expandedRendered=!1})}}}}}]),e.directive("uiGridRow",["$compile","gridUtil","$templateCache",function(e,n,o){return{priority:-200,scope:!1,compile:function(e,n){return{pre:function(e,n,o,i){e.grid.options.enableExpandable&&(e.expandableRow={},e.expandableRow.shouldRenderExpand=function(){return"body"===e.colContainer.name&&!1!==e.grid.options.enableExpandable&&e.row.isExpanded&&(!e.grid.isScrollingVertically||e.row.expandedRendered)},e.expandableRow.shouldRenderFiller=function(){return e.row.isExpanded&&("body"!==e.colContainer.name||e.grid.isScrollingVertically&&!e.row.expandedRendered)})},post:function(e,n,o,i){}}}}}]),e.directive("uiGridViewport",["$compile","gridUtil","$templateCache",function(e,n,d){return{priority:-200,scope:!1,compile:function(e,n){var o=angular.element(e.children().children()[0]),i=d.get("ui-grid/expandableScrollFiller"),a=d.get("ui-grid/expandableRow");return o.append(a),o.append(i),{pre:function(e,n,o,i){},post:function(e,n,o,i){}}}}}])}();
\ No newline at end of file
diff --git a/release/4.4.11/ui-grid.exporter.js b/release/4.4.11/ui-grid.exporter.js
new file mode 100644
index 000000000..cb4c03133
--- /dev/null
+++ b/release/4.4.11/ui-grid.exporter.js
@@ -0,0 +1,1739 @@
+/*!
+ * ui-grid - v4.4.11 - 2018-05-16
+ * Copyright (c) 2018 ; License: MIT
+ */
+
+/* global ExcelBuilder */
+/* global console */
+
+(function () {
+ 'use strict';
+
+ /**
+ * @ngdoc overview
+ * @name ui.grid.exporter
+ * @description
+ *
+ * # ui.grid.exporter
+ *
+ *
+ *
+ *
+ *
+ */
+
+ var module = angular.module('ui.grid.exporter', ['ui.grid']);
+
+ /**
+ * @ngdoc object
+ * @name ui.grid.exporter.constant:uiGridExporterConstants
+ *
+ * @description constants available in exporter module
+ */
+ /**
+ * @ngdoc property
+ * @propertyOf ui.grid.exporter.constant:uiGridExporterConstants
+ * @name ALL
+ * @description export all data, including data not visible. Can
+ * be set for either rowTypes or colTypes
+ */
+ /**
+ * @ngdoc property
+ * @propertyOf ui.grid.exporter.constant:uiGridExporterConstants
+ * @name VISIBLE
+ * @description export only visible data, including data not visible. Can
+ * be set for either rowTypes or colTypes
+ */
+ /**
+ * @ngdoc property
+ * @propertyOf ui.grid.exporter.constant:uiGridExporterConstants
+ * @name SELECTED
+ * @description export all data, including data not visible. Can
+ * be set only for rowTypes, selection of only some columns is
+ * not supported
+ */
+ module.constant('uiGridExporterConstants', {
+ featureName: 'exporter',
+ rowHeaderColName: 'treeBaseRowHeaderCol',
+ selectionRowHeaderColName: 'selectionRowHeaderCol',
+ ALL: 'all',
+ VISIBLE: 'visible',
+ SELECTED: 'selected',
+ CSV_CONTENT: 'CSV_CONTENT',
+ BUTTON_LABEL: 'BUTTON_LABEL',
+ FILE_NAME: 'FILE_NAME'
+ });
+
+ /**
+ * @ngdoc service
+ * @name ui.grid.exporter.service:uiGridExporterService
+ *
+ * @description Services for exporter feature
+ */
+ module.service('uiGridExporterService', ['$filter', '$q', 'uiGridExporterConstants', 'gridUtil', '$compile', '$interval', 'i18nService',
+ function ($filter, $q, uiGridExporterConstants, gridUtil, $compile, $interval, i18nService) {
+ var service = {
+
+ delay: 100,
+
+ initializeGrid: function (grid) {
+
+ //add feature namespace and any properties to grid for needed state
+ grid.exporter = {};
+ this.defaultGridOptions(grid.options);
+
+ /**
+ * @ngdoc object
+ * @name ui.grid.exporter.api:PublicApi
+ *
+ * @description Public Api for exporter feature
+ */
+ var publicApi = {
+ events: {
+ exporter: {
+ }
+ },
+ methods: {
+ exporter: {
+ /**
+ * @ngdoc function
+ * @name csvExport
+ * @methodOf ui.grid.exporter.api:PublicApi
+ * @description Exports rows from the grid in csv format,
+ * the data exported is selected based on the provided options
+ * @param {string} rowTypes which rows to export, valid values are
+ * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
+ * uiGridExporterConstants.SELECTED
+ * @param {string} colTypes which columns to export, valid values are
+ * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE
+ */
+ csvExport: function (rowTypes, colTypes) {
+ service.csvExport(grid, rowTypes, colTypes);
+ },
+ /**
+ * @ngdoc function
+ * @name pdfExport
+ * @methodOf ui.grid.exporter.api:PublicApi
+ * @description Exports rows from the grid in pdf format,
+ * the data exported is selected based on the provided options
+ * Note that this function has a dependency on pdfMake, all
+ * going well this has been installed for you.
+ * The resulting pdf opens in a new browser window.
+ * @param {string} rowTypes which rows to export, valid values are
+ * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
+ * uiGridExporterConstants.SELECTED
+ * @param {string} colTypes which columns to export, valid values are
+ * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE
+ */
+ pdfExport: function (rowTypes, colTypes) {
+ service.pdfExport(grid, rowTypes, colTypes);
+ },
+ /**
+ * @ngdoc function
+ * @name excelExport
+ * @methodOf ui.grid.exporter.api:PublicApi
+ * @description Exports rows from the grid in excel format,
+ * the data exported is selected based on the provided options
+ * @param {string} rowTypes which rows to export, valid values are
+ * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
+ * uiGridExporterConstants.SELECTED
+ * @param {string} colTypes which columns to export, valid values are
+ * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE
+ */
+ excelExport: function (rowTypes, colTypes) {
+ service.excelExport(grid, rowTypes, colTypes);
+ }
+ }
+ }
+ };
+
+ grid.api.registerEventsFromObject(publicApi.events);
+
+ grid.api.registerMethodsFromObject(publicApi.methods);
+
+ if (grid.api.core.addToGridMenu){
+ service.addToMenu( grid );
+ } else {
+ // order of registration is not guaranteed, register in a little while
+ $interval( function() {
+ if (grid.api.core.addToGridMenu){
+ service.addToMenu( grid );
+ }
+ }, this.delay, 1);
+ }
+
+ },
+
+ defaultGridOptions: function (gridOptions) {
+ //default option to true unless it was explicitly set to false
+ /**
+ * @ngdoc object
+ * @name ui.grid.exporter.api:GridOptions
+ *
+ * @description GridOptions for exporter feature, these are available to be
+ * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
+ */
+ /**
+ * @ngdoc object
+ * @name ui.grid.exporter.api:ColumnDef
+ * @description ColumnDef settings for exporter
+ */
+ /**
+ * @ngdoc object
+ * @name exporterSuppressMenu
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description Don't show the export menu button, implying the user
+ * will roll their own UI for calling the exporter
+ *
Defaults to false
+ */
+ gridOptions.exporterSuppressMenu = gridOptions.exporterSuppressMenu === true;
+ /**
+ * @ngdoc object
+ * @name exporterMenuLabel
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description The text to show on the exporter menu button
+ * link
+ *
Defaults to 'Export'
+ */
+ gridOptions.exporterMenuLabel = gridOptions.exporterMenuLabel ? gridOptions.exporterMenuLabel : 'Export';
+ /**
+ * @ngdoc object
+ * @name exporterSuppressColumns
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description Columns that should not be exported. The selectionRowHeader is already automatically
+ * suppressed, but if you had a button column or some other "system" column that shouldn't be shown in the
+ * output then add it in this list. You should provide an array of column names.
+ *
Defaults to: []
+ *
+ * gridOptions.exporterSuppressColumns = [ 'buttons' ];
+ *
+ */
+ gridOptions.exporterSuppressColumns = gridOptions.exporterSuppressColumns ? gridOptions.exporterSuppressColumns : [];
+ /**
+ * @ngdoc object
+ * @name exporterCsvColumnSeparator
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description The character to use as column separator
+ * link
+ *
Defaults to ','
+ */
+ gridOptions.exporterCsvColumnSeparator = gridOptions.exporterCsvColumnSeparator ? gridOptions.exporterCsvColumnSeparator : ',';
+ /**
+ * @ngdoc object
+ * @name exporterCsvFilename
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description The default filename to use when saving the downloaded csv.
+ * This will only work in some browsers.
+ *
Defaults to 'download.csv'
+ */
+ gridOptions.exporterCsvFilename = gridOptions.exporterCsvFilename ? gridOptions.exporterCsvFilename : 'download.csv';
+ /**
+ * @ngdoc object
+ * @name exporterPdfFilename
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description The default filename to use when saving the downloaded pdf, only used in IE (other browsers open pdfs in a new window)
+ *
Defaults to 'download.pdf'
+ */
+ gridOptions.exporterPdfFilename = gridOptions.exporterPdfFilename ? gridOptions.exporterPdfFilename : 'download.pdf';
+ /**
+ * @ngdoc object
+ * @name exporterExcelFilename
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description The default filename to use when saving the downloaded excel, only used in IE (other browsers open excels in a new window)
+ *
Defaults to 'download.xlsx'
+ */
+ gridOptions.exporterExcelFilename = gridOptions.exporterExcelFilename ? gridOptions.exporterExcelFilename : 'download.xlsx';
+
+ /**
+ * @ngdoc object
+ * @name exporterExcelSheetName
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description The default sheetname to use when saving the downloaded to excel
+ *
Defaults to 'Sheet1'
+ */
+ gridOptions.exporterExcelSheetName = gridOptions.exporterExcelSheetName ? gridOptions.exporterExcelSheetName : 'Sheet1';
+
+ /**
+ * @ngdoc object
+ * @name exporterOlderExcelCompatibility
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description Some versions of excel don't like the utf-16 BOM on the front, and it comes
+ * through as  in the first column header. Setting this option to false will suppress this, at the
+ * expense of proper utf-16 handling in applications that do recognise the BOM
+ *
Defaults to false
+ */
+ gridOptions.exporterOlderExcelCompatibility = gridOptions.exporterOlderExcelCompatibility === true;
+ /**
+ * @ngdoc object
+ * @name exporterIsExcelCompatible
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description Separator header, used to set a custom column separator in a csv file, only works on MS Excel.
+ * Used it on other programs will make csv content display unproperly. Setting this option to false won't add this header.
+ *
Defaults to false
+ */
+ gridOptions.exporterIsExcelCompatible = gridOptions.exporterIsExcelCompatible === true;
+ /**
+ * @ngdoc object
+ * @name exporterMenuItemOrder
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description An option to determine the starting point for the menu items created by the exporter
+ *
Defaults to 200
+ */
+ gridOptions.exporterMenuItemOrder = gridOptions.exporterMenuItemOrder ? gridOptions.exporterMenuItemOrder : 200;
+ /**
+ * @ngdoc object
+ * @name exporterPdfDefaultStyle
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description The default style in pdfMake format
+ *
Defaults to:
+ *
+ * {
+ * fontSize: 11
+ * }
+ *
+ */
+ gridOptions.exporterPdfDefaultStyle = gridOptions.exporterPdfDefaultStyle ? gridOptions.exporterPdfDefaultStyle : { fontSize: 11 };
+ /**
+ * @ngdoc object
+ * @name exporterPdfTableStyle
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description The table style in pdfMake format
+ *
Defaults to:
+ *
+ * {
+ * margin: [0, 5, 0, 15]
+ * }
+ *
+ */
+ gridOptions.exporterPdfTableStyle = gridOptions.exporterPdfTableStyle ? gridOptions.exporterPdfTableStyle : { margin: [0, 5, 0, 15] };
+ /**
+ * @ngdoc object
+ * @name exporterPdfTableHeaderStyle
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description The tableHeader style in pdfMake format
+ *
Defaults to:
+ *
+ * {
+ * bold: true,
+ * fontSize: 12,
+ * color: 'black'
+ * }
+ *
+ */
+ gridOptions.exporterPdfTableHeaderStyle = gridOptions.exporterPdfTableHeaderStyle ? gridOptions.exporterPdfTableHeaderStyle : { bold: true, fontSize: 12, color: 'black' };
+ /**
+ * @ngdoc object
+ * @name exporterPdfHeader
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description The header section for pdf exports. Can be
+ * simple text:
+ *
+ * gridOptions.exporterPdfHeader = 'My Header';
+ *
+ * Can be a more complex object in pdfMake format:
+ *
+ * gridOptions.exporterPdfHeader = {
+ * columns: [
+ * 'Left part',
+ * { text: 'Right part', alignment: 'right' }
+ * ]
+ * };
+ *
+ * Or can be a function, allowing page numbers and the like
+ *
+ * gridOptions.exporterPdfHeader: function(currentPage, pageCount) { return currentPage.toString() + ' of ' + pageCount; };
+ *
+ */
+ gridOptions.exporterPdfHeader = gridOptions.exporterPdfHeader ? gridOptions.exporterPdfHeader : null;
+ /**
+ * @ngdoc object
+ * @name exporterPdfFooter
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description The header section for pdf exports. Can be
+ * simple text:
+ *
+ * gridOptions.exporterPdfFooter = 'My Footer';
+ *
+ * Can be a more complex object in pdfMake format:
+ *
+ * gridOptions.exporterPdfFooter = {
+ * columns: [
+ * 'Left part',
+ * { text: 'Right part', alignment: 'right' }
+ * ]
+ * };
+ *
+ * Or can be a function, allowing page numbers and the like
+ *
+ * gridOptions.exporterPdfFooter: function(currentPage, pageCount) { return currentPage.toString() + ' of ' + pageCount; };
+ *
+ */
+ gridOptions.exporterPdfFooter = gridOptions.exporterPdfFooter ? gridOptions.exporterPdfFooter : null;
+ /**
+ * @ngdoc object
+ * @name exporterPdfOrientation
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description The orientation, should be a valid pdfMake value,
+ * 'landscape' or 'portrait'
+ *
Defaults to landscape
+ */
+ gridOptions.exporterPdfOrientation = gridOptions.exporterPdfOrientation ? gridOptions.exporterPdfOrientation : 'landscape';
+ /**
+ * @ngdoc object
+ * @name exporterPdfPageSize
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description The orientation, should be a valid pdfMake
+ * paper size, usually 'A4' or 'LETTER'
+ * {@link https://github.com/bpampuch/pdfmake/blob/master/src/standardPageSizes.js pdfMake page sizes}
+ *
Defaults to A4
+ */
+ gridOptions.exporterPdfPageSize = gridOptions.exporterPdfPageSize ? gridOptions.exporterPdfPageSize : 'A4';
+ /**
+ * @ngdoc object
+ * @name exporterPdfMaxGridWidth
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description The maxium grid width - the current grid width
+ * will be scaled to match this, with any fixed width columns
+ * being adjusted accordingly.
+ *
Defaults to 720 (for A4 landscape), use 670 for LETTER
+ */
+ gridOptions.exporterPdfMaxGridWidth = gridOptions.exporterPdfMaxGridWidth ? gridOptions.exporterPdfMaxGridWidth : 720;
+ /**
+ * @ngdoc object
+ * @name exporterPdfTableLayout
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description A tableLayout in pdfMake format,
+ * controls gridlines and the like. We use the default
+ * layout usually.
+ *
Defaults to null, which means no layout
+ */
+
+ /**
+ * @ngdoc object
+ * @name exporterMenuAllData
+ * @porpertyOf ui.grid.exporter.api:GridOptions
+ * @description Add export all data as cvs/pdf menu items to the ui-grid grid menu, if it's present. Defaults to true.
+ */
+ gridOptions.exporterMenuAllData = gridOptions.exporterMenuAllData !== undefined ? gridOptions.exporterMenuAllData : true;
+
+ /**
+ * @ngdoc object
+ * @name exporterMenuVisibleData
+ * @porpertyOf ui.grid.exporter.api:GridOptions
+ * @description Add export visible data as cvs/pdf menu items to the ui-grid grid menu, if it's present. Defaults to true.
+ */
+ gridOptions.exporterMenuVisibleData = gridOptions.exporterMenuVisibleData !== undefined ? gridOptions.exporterMenuVisibleData : true;
+
+ /**
+ * @ngdoc object
+ * @name exporterMenuSelectedData
+ * @porpertyOf ui.grid.exporter.api:GridOptions
+ * @description Add export selected data as cvs/pdf menu items to the ui-grid grid menu, if it's present. Defaults to true.
+ */
+ gridOptions.exporterMenuSelectedData = gridOptions.exporterMenuSelectedData !== undefined ? gridOptions.exporterMenuSelectedData : true;
+
+ /**
+ * @ngdoc object
+ * @name exporterMenuCsv
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description Add csv export menu items to the ui-grid grid menu, if it's present. Defaults to true.
+ */
+ gridOptions.exporterMenuCsv = gridOptions.exporterMenuCsv !== undefined ? gridOptions.exporterMenuCsv : true;
+
+ /**
+ * @ngdoc object
+ * @name exporterMenuPdf
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description Add pdf export menu items to the ui-grid grid menu, if it's present. Defaults to true.
+ */
+ gridOptions.exporterMenuPdf = gridOptions.exporterMenuPdf !== undefined ? gridOptions.exporterMenuPdf : true;
+
+ /**
+ * @ngdoc object
+ * @name exporterMenuExcel
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description Add excel export menu items to the ui-grid grid menu, if it's present. Defaults to true.
+ */
+ gridOptions.exporterMenuExcel = gridOptions.exporterMenuExcel !== undefined ? gridOptions.exporterMenuExcel : true;
+
+ /**
+ * @ngdoc object
+ * @name exporterPdfCustomFormatter
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description A custom callback routine that changes the pdf document, adding any
+ * custom styling or content that is supported by pdfMake. Takes in the complete docDefinition, and
+ * must return an updated docDefinition ready for pdfMake.
+ * @example
+ * In this example we add a style to the style array, so that we can use it in our
+ * footer definition.
+ *
+ * gridOptions.exporterPdfCustomFormatter = function ( docDefinition ) {
+ * docDefinition.styles.footerStyle = { bold: true, fontSize: 10 };
+ * return docDefinition;
+ * }
+ *
+ * gridOptions.exporterPdfFooter = { text: 'My footer', style: 'footerStyle' }
+ *
+ */
+ gridOptions.exporterPdfCustomFormatter = ( gridOptions.exporterPdfCustomFormatter && typeof( gridOptions.exporterPdfCustomFormatter ) === 'function' ) ? gridOptions.exporterPdfCustomFormatter : function ( docDef ) { return docDef; };
+
+ /**
+ * @ngdoc object
+ * @name exporterHeaderFilterUseName
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description Defaults to false, which leads to `displayName` being passed into the headerFilter.
+ * If set to true, then will pass `name` instead.
+ *
+ *
+ * @example
+ *
+ * gridOptions.exporterHeaderFilterUseName = true;
+ *
+ */
+ gridOptions.exporterHeaderFilterUseName = gridOptions.exporterHeaderFilterUseName === true;
+
+ /**
+ * @ngdoc object
+ * @name exporterHeaderFilter
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description A function to apply to the header displayNames before exporting. Useful for internationalisation,
+ * for example if you were using angular-translate you'd set this to `$translate.instant`. Note that this
+ * call must be synchronous, it cannot be a call that returns a promise.
+ *
+ * Behaviour can be changed to pass in `name` instead of `displayName` through use of `exporterHeaderFilterUseName: true`.
+ *
+ * @example
+ *
+ * gridOptions.exporterHeaderFilter = function( displayName ){ return 'col: ' + name; };
+ *
+ * OR
+ *
+ * gridOptions.exporterHeaderFilter = $translate.instant;
+ *
+ */
+
+ /**
+ * @ngdoc function
+ * @name exporterFieldCallback
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description A function to call for each field before exporting it. Allows
+ * massaging of raw data into a display format, for example if you have applied
+ * filters to convert codes into decodes, or you require
+ * a specific date format in the exported content.
+ *
+ * The method is called once for each field exported, and provides the grid, the
+ * gridCol and the GridRow for you to use as context in massaging the data.
+ *
+ * @param {Grid} grid provides the grid in case you have need of it
+ * @param {GridRow} row the row from which the data comes
+ * @param {GridColumn} col the column from which the data comes
+ * @param {object} value the value for your massaging
+ * @returns {object} you must return the massaged value ready for exporting
+ *
+ * @example
+ *
+ * gridOptions.exporterFieldCallback = function ( grid, row, col, value ){
+ * if ( col.name === 'status' ){
+ * value = decodeStatus( value );
+ * }
+ * return value;
+ * }
+ *
+ */
+ gridOptions.exporterFieldCallback = gridOptions.exporterFieldCallback ? gridOptions.exporterFieldCallback : defaultExporterFieldCallback;
+
+ /**
+ * @ngdoc function
+ * @name exporterFieldFormatCallback
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description A function to call for each field before exporting it. Allows
+ * general object to be return to modify the format of a cell in the case of
+ * excel exports
+ *
+ * The method is called once for each field exported, and provides the grid, the
+ * gridCol and the GridRow for you to use as context in massaging the data.
+ *
+ * @param {Grid} grid provides the grid in case you have need of it
+ * @param {GridRow} row the row from which the data comes
+ * @param {GridColumn} col the column from which the data comes
+ * @param {object} value the value for your massaging
+ * @returns {object} you must return the massaged value ready for exporting
+ *
+ * @example
+ *
+ * gridOptions.exporterFieldCallback = function ( grid, row, col, value ){
+ * if ( col.name === 'status' ){
+ * value = decodeStatus( value );
+ * }
+ * return value;
+ * }
+ *
+ */
+ gridOptions.exporterFieldFormatCallback = gridOptions.exporterFieldFormatCallback ? gridOptions.exporterFieldFormatCallback : function( grid, row, col, value ) { return null; };
+
+ /**
+ * @ngdoc function
+ * @name exporterExcelCustomFormatters
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description A function to call to setup formatters and store on docDefinition.
+ *
+ * The method is called at the start and can setup all the formatters to export to excel
+ *
+ * @param {Grid} grid provides the grid in case you have need of it
+ * @param {Workbook} row the row from which the data comes
+ * @param {docDefinition} The docDefinition that will have styles as a object to store formatters
+ * @returns {docDefinition} Updated docDefinition with formatter styles
+ *
+ * @example
+ *
+ * gridOptions.exporterExcelCustomFormatters = function(grid, workbook, docDefinition) {
+ * const formatters = {};
+ * const stylesheet = workbook.getStyleSheet();
+ * const headerFormatDefn = {
+ * 'font': { 'size': 11, 'fontName': 'Calibri', 'bold': true },
+ * 'alignment': { 'wrapText': false }
+ * };
+ *
+ * formatters['header'] = headerFormatter;
+ * Object.assign(docDefinition.styles , formatters);
+ * grid.docDefinition = docDefinition;
+ * return docDefinition;
+ * }
+ *
+ */
+ gridOptions.exporterExcelCustomFormatters = gridOptions.exporterExcelCustomFormatters ? gridOptions.exporterExcelCustomFormatters : function( grid, workbook, docDefinition ) { return null; };
+
+ /**
+ * @ngdoc function
+ * @name exporterExcelHeader
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description A function to write formatted header data to sheet.
+ *
+ * The method is called to provide custom header building for Excel. This data comes before the grid header
+ *
+ * @param {grid} grid provides the grid in case you have need of it
+ * @param {Workbook} row the row from which the data comes
+ * @param {Sheet} the sheet to insert data
+ * @param {docDefinition} The docDefinition that will have styles as a object to store formatters
+ * @returns {docDefinition} Updated docDefinition with formatter styles
+ *
+ * @example
+ *
+ * gridOptions.exporterExcelCustomFormatters = function (grid, workbook, sheet, docDefinition) {
+ * const headerFormatter = docDefinition.styles['header'];
+ * let cols = [];
+ * // push data in A1 cell with metadata formatter
+ * cols.push({ value: 'Summary Report', metadata: {style: headerFormatter.id} });
+ * sheet.data.push(cols);
+ * }
+ *
+ */
+ gridOptions.exporterExcelHeader = gridOptions.exporterExcelHeader ? gridOptions.exporterExcelHeader : function( grid, workbook, sheet, docDefinition ) { return null; };
+
+
+ /**
+ * @ngdoc object
+ * @name exporterColumnScaleFactor
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description A scaling factor to divide the drawnwidth of a column to convert to target excel column
+ * format size
+ * @example
+ * In this example we add a number to divide the drawnwidth of a column to get the excel width.
+ *
Defaults to 3.5
+ */
+ gridOptions.exporterColumnScaleFactor = gridOptions.exporterColumnScaleFactor ? gridOptions.exporterColumnScaleFactor : 3.5;
+
+ /**
+ * @ngdoc object
+ * @name exporterFieldApplyFilters
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description Defaults to false, which leads to filters being evaluated on export *
+ *
+ * @example
+ *
+ * gridOptions.exporterFieldApplyFilters = true;
+ *
+ */
+ gridOptions.exporterFieldApplyFilters = gridOptions.exporterFieldApplyFilters === true;
+
+ /**
+ * @ngdoc function
+ * @name exporterAllDataFn
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description This promise is needed when exporting all rows,
+ * and the data need to be provided by server side. Default is null.
+ * @returns {Promise} a promise to load all data from server
+ *
+ * @example
+ *
+ * gridOptions.exporterAllDataFn = function () {
+ * return $http.get('/data/100.json')
+ * }
+ *
+ */
+ gridOptions.exporterAllDataFn = gridOptions.exporterAllDataFn ? gridOptions.exporterAllDataFn : null;
+
+ /**
+ * @ngdoc function
+ * @name exporterAllDataPromise
+ * @propertyOf ui.grid.exporter.api:GridOptions
+ * @description DEPRECATED - exporterAllDataFn used to be
+ * called this, but it wasn't a promise, it was a function that returned
+ * a promise. Deprecated, but supported for backward compatibility, use
+ * exporterAllDataFn instead.
+ * @returns {Promise} a promise to load all data from server
+ *
+ * @example
+ *
+ * gridOptions.exporterAllDataFn = function () {
+ * return $http.get('/data/100.json')
+ * }
+ *
+ */
+ if ( gridOptions.exporterAllDataFn === null && gridOptions.exporterAllDataPromise ) {
+ gridOptions.exporterAllDataFn = gridOptions.exporterAllDataPromise;
+ }
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name addToMenu
+ * @methodOf ui.grid.exporter.service:uiGridExporterService
+ * @description Adds export items to the grid menu,
+ * allowing the user to select export options
+ * @param {Grid} grid the grid from which data should be exported
+ */
+ addToMenu: function ( grid ) {
+ grid.api.core.addToGridMenu( grid, [
+ {
+ title: i18nService.getSafeText('gridMenu.exporterAllAsCsv'),
+ action: function ($event) {
+ grid.api.exporter.csvExport( uiGridExporterConstants.ALL, uiGridExporterConstants.ALL );
+ },
+ shown: function() {
+ return grid.options.exporterMenuCsv && grid.options.exporterMenuAllData;
+ },
+ order: grid.options.exporterMenuItemOrder
+ },
+ {
+ title: i18nService.getSafeText('gridMenu.exporterVisibleAsCsv'),
+ action: function ($event) {
+ grid.api.exporter.csvExport( uiGridExporterConstants.VISIBLE, uiGridExporterConstants.VISIBLE );
+ },
+ shown: function() {
+ return grid.options.exporterMenuCsv && grid.options.exporterMenuVisibleData;
+ },
+ order: grid.options.exporterMenuItemOrder + 1
+ },
+ {
+ title: i18nService.getSafeText('gridMenu.exporterSelectedAsCsv'),
+ action: function ($event) {
+ grid.api.exporter.csvExport( uiGridExporterConstants.SELECTED, uiGridExporterConstants.VISIBLE );
+ },
+ shown: function() {
+ return grid.options.exporterMenuCsv && grid.options.exporterMenuSelectedData &&
+ ( grid.api.selection && grid.api.selection.getSelectedRows().length > 0 );
+ },
+ order: grid.options.exporterMenuItemOrder + 2
+ },
+ {
+ title: i18nService.getSafeText('gridMenu.exporterAllAsPdf'),
+ action: function ($event) {
+ grid.api.exporter.pdfExport( uiGridExporterConstants.ALL, uiGridExporterConstants.ALL );
+ },
+ shown: function() {
+ return grid.options.exporterMenuPdf && grid.options.exporterMenuAllData;
+ },
+ order: grid.options.exporterMenuItemOrder + 3
+ },
+ {
+ title: i18nService.getSafeText('gridMenu.exporterVisibleAsPdf'),
+ action: function ($event) {
+ grid.api.exporter.pdfExport( uiGridExporterConstants.VISIBLE, uiGridExporterConstants.VISIBLE );
+ },
+ shown: function() {
+ return grid.options.exporterMenuPdf && grid.options.exporterMenuVisibleData;
+ },
+ order: grid.options.exporterMenuItemOrder + 4
+ },
+ {
+ title: i18nService.getSafeText('gridMenu.exporterSelectedAsPdf'),
+ action: function ($event) {
+ grid.api.exporter.pdfExport( uiGridExporterConstants.SELECTED, uiGridExporterConstants.VISIBLE );
+ },
+ shown: function() {
+ return grid.options.exporterMenuPdf && grid.options.exporterMenuSelectedData &&
+ ( grid.api.selection && grid.api.selection.getSelectedRows().length > 0 );
+ },
+ order: grid.options.exporterMenuItemOrder + 5
+ },
+ {
+ title: i18nService.getSafeText('gridMenu.exporterAllAsExcel'),
+ action: function ($event) {
+ grid.api.exporter.excelExport( uiGridExporterConstants.ALL, uiGridExporterConstants.ALL );
+ },
+ shown: function() {
+ return grid.options.exporterMenuExcel && grid.options.exporterMenuAllData;
+ },
+ order: grid.options.exporterMenuItemOrder + 6
+ },
+ {
+ title: i18nService.getSafeText('gridMenu.exporterVisibleAsExcel'),
+ action: function ($event) {
+ grid.api.exporter.excelExport( uiGridExporterConstants.VISIBLE, uiGridExporterConstants.VISIBLE );
+ },
+ shown: function() {
+ return grid.options.exporterMenuExcel && grid.options.exporterMenuVisibleData;
+ },
+ order: grid.options.exporterMenuItemOrder + 7
+ },
+ {
+ title: i18nService.getSafeText('gridMenu.exporterSelectedAsExcel'),
+ action: function ($event) {
+ grid.api.exporter.excelExport( uiGridExporterConstants.SELECTED, uiGridExporterConstants.VISIBLE );
+ },
+ shown: function() {
+ return grid.options.exporterMenuExcel && grid.options.exporterMenuSelectedData &&
+ ( grid.api.selection && grid.api.selection.getSelectedRows().length > 0 );
+ },
+ order: grid.options.exporterMenuItemOrder + 8
+ }
+ ]);
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name csvExport
+ * @methodOf ui.grid.exporter.service:uiGridExporterService
+ * @description Exports rows from the grid in csv format,
+ * the data exported is selected based on the provided options
+ * @param {Grid} grid the grid from which data should be exported
+ * @param {string} rowTypes which rows to export, valid values are
+ * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
+ * uiGridExporterConstants.SELECTED
+ * @param {string} colTypes which columns to export, valid values are
+ * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
+ * uiGridExporterConstants.SELECTED
+ */
+ csvExport: function (grid, rowTypes, colTypes) {
+ var self = this;
+ this.loadAllDataIfNeeded(grid, rowTypes, colTypes).then(function() {
+ var exportColumnHeaders = grid.options.showHeader ? self.getColumnHeaders(grid, colTypes) : [];
+ var exportData = self.getData(grid, rowTypes, colTypes);
+ var csvContent = self.formatAsCsv(exportColumnHeaders, exportData, grid.options.exporterCsvColumnSeparator);
+
+ self.downloadFile (grid.options.exporterCsvFilename, csvContent, grid.options.exporterCsvColumnSeparator, grid.options.exporterOlderExcelCompatibility, grid.options.exporterIsExcelCompatible);
+ });
+ },
+
+ /**
+ * @ngdoc function
+ * @name loadAllDataIfNeeded
+ * @methodOf ui.grid.exporter.service:uiGridExporterService
+ * @description When using server side pagination, use exporterAllDataFn to
+ * load all data before continuing processing.
+ * When using client side pagination, return a resolved promise so processing
+ * continues immediately
+ * @param {Grid} grid the grid from which data should be exported
+ * @param {string} rowTypes which rows to export, valid values are
+ * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
+ * uiGridExporterConstants.SELECTED
+ * @param {string} colTypes which columns to export, valid values are
+ * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
+ * uiGridExporterConstants.SELECTED
+ */
+ loadAllDataIfNeeded: function (grid, rowTypes, colTypes) {
+ if ( rowTypes === uiGridExporterConstants.ALL && grid.rows.length !== grid.options.totalItems && grid.options.exporterAllDataFn) {
+ return grid.options.exporterAllDataFn()
+ .then(function(allData) {
+ grid.modifyRows(allData);
+ });
+ } else {
+ var deferred = $q.defer();
+ deferred.resolve();
+ return deferred.promise;
+ }
+ },
+
+ /**
+ * @ngdoc property
+ * @propertyOf ui.grid.exporter.api:ColumnDef
+ * @name exporterSuppressExport
+ * @description Suppresses export for this column. Used by selection and expandable.
+ */
+
+ /**
+ * @ngdoc function
+ * @name getColumnHeaders
+ * @methodOf ui.grid.exporter.service:uiGridExporterService
+ * @description Gets the column headers from the grid to use
+ * as a title row for the exported file, all headers have
+ * headerCellFilters applied as appropriate.
+ *
+ * Column headers are an array of objects, each object has
+ * name, displayName, width and align attributes. Only name is
+ * used for csv, all attributes are used for pdf.
+ *
+ * @param {Grid} grid the grid from which data should be exported
+ * @param {string} colTypes which columns to export, valid values are
+ * uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE,
+ * uiGridExporterConstants.SELECTED
+ */
+ getColumnHeaders: function (grid, colTypes) {
+ var headers = [];
+ var columns;
+
+ if ( colTypes === uiGridExporterConstants.ALL ){
+ columns = grid.columns;
+ } else {
+ var leftColumns = grid.renderContainers.left ? grid.renderContainers.left.visibleColumnCache.filter( function( column ){ return column.visible; } ) : [];
+ var bodyColumns = grid.renderContainers.body ? grid.renderContainers.body.visibleColumnCache.filter( function( column ){ return column.visible; } ) : [];
+ var rightColumns = grid.renderContainers.right ? grid.renderContainers.right.visibleColumnCache.filter( function( column ){ return column.visible; } ) : [];
+
+ columns = leftColumns.concat(bodyColumns,rightColumns);
+ }
+
+ columns.forEach( function( gridCol ) {
+ // $$hashKey check since when grouping and sorting pragmatically this ends up in export. Filtering it out
+ if ( gridCol.colDef.exporterSuppressExport !== true && gridCol.field !== '$$hashKey' &&
+ grid.options.exporterSuppressColumns.indexOf( gridCol.name ) === -1 ){
+ var headerEntry = {
+ name: gridCol.field,
+ displayName: getDisplayName(grid, gridCol),
+ width: gridCol.drawnWidth ? gridCol.drawnWidth : gridCol.width,
+ align: gridCol.colDef.align ? gridCol.colDef.align : (gridCol.colDef.type === 'number' ? 'right' : 'left')
+ };
+ headers.push(headerEntry);
+ }
+ });
+
+ return headers;
+ },
+
+
+ /**
+ * @ngdoc property
+ * @propertyOf ui.grid.exporter.api:ColumnDef
+ * @name exporterPdfAlign
+ * @description the alignment you'd like for this specific column when
+ * exported into a pdf. Can be 'left', 'right', 'center' or any other
+ * valid pdfMake alignment option.
+ */
+
+
+ /**
+ * @ngdoc object
+ * @name ui.grid.exporter.api:GridRow
+ * @description GridRow settings for exporter
+ */
+ /**
+ * @ngdoc object
+ * @name exporterEnableExporting
+ * @propertyOf ui.grid.exporter.api:GridRow
+ * @description If set to false, then don't export this row, notwithstanding visible or
+ * other settings
+ *
Defaults to true
+ */
+
+
+ /**
+ * @ngdoc function
+ * @name getRowsFromNode
+ * @methodOf ui.grid.exporter.service:uiGridExporterService
+ * @description Gets rows from a node. If the node is grouped it will
+ * recurse down into the children to get to the raw data element
+ * which is a row without children (a leaf).
+ * @param {Node} aNode the tree node on the grid
+ * @returns {Array} an array of leaf nodes
+ */
+ getRowsFromNode: function(aNode) {
+ var rows = [];
+ for (var i = 0; i
+ *
+ *
+ *
+ */
+
+ var module = angular.module('ui.grid.grouping', ['ui.grid', 'ui.grid.treeBase']);
+
+ /**
+ * @ngdoc object
+ * @name ui.grid.grouping.constant:uiGridGroupingConstants
+ *
+ * @description constants available in grouping module, this includes
+ * all the constants declared in the treeBase module (these are manually copied
+ * as there isn't an easy way to include constants in another constants file, and
+ * we don't want to make users include treeBase)
+ *
+ */
+ module.constant('uiGridGroupingConstants', {
+ featureName: "grouping",
+ rowHeaderColName: 'treeBaseRowHeaderCol',
+ EXPANDED: 'expanded',
+ COLLAPSED: 'collapsed',
+ aggregation: {
+ COUNT: 'count',
+ SUM: 'sum',
+ MAX: 'max',
+ MIN: 'min',
+ AVG: 'avg'
+ }
+ });
+
+ /**
+ * @ngdoc service
+ * @name ui.grid.grouping.service:uiGridGroupingService
+ *
+ * @description Services for grouping features
+ */
+ module.service('uiGridGroupingService', ['$q', 'uiGridGroupingConstants', 'gridUtil', 'rowSorter', 'GridRow', 'gridClassFactory', 'i18nService', 'uiGridConstants', 'uiGridTreeBaseService',
+ function ($q, uiGridGroupingConstants, gridUtil, rowSorter, GridRow, gridClassFactory, i18nService, uiGridConstants, uiGridTreeBaseService) {
+
+ var service = {
+
+ initializeGrid: function (grid, $scope) {
+ uiGridTreeBaseService.initializeGrid( grid, $scope );
+
+ //add feature namespace and any properties to grid for needed
+ /**
+ * @ngdoc object
+ * @name ui.grid.grouping.grid:grouping
+ *
+ * @description Grid properties and functions added for grouping
+ */
+ grid.grouping = {};
+
+ /**
+ * @ngdoc property
+ * @propertyOf ui.grid.grouping.grid:grouping
+ * @name groupHeaderCache
+ *
+ * @description Cache that holds the group header rows we created last time, we'll
+ * reuse these next time, not least because they hold our expanded states.
+ *
+ * We need to take care with these that they don't become a memory leak, we
+ * create a new cache each time using the values from the old cache. This works
+ * so long as we're creating group rows for invisible rows as well.
+ *
+ * The cache is a nested hash, indexed on the value we grouped by. So if we
+ * grouped by gender then age, we'd maybe have something like:
+ * ```
+ * {
+ * male: {
+ * row:
+ * gridApi.grouping.on.aggregationChanged(scope,function(col){})
+ *
+ * @param {GridColumn} col the column which on which aggregation changed. The aggregation
+ * type is available as `col.treeAggregation.type`
+ */
+ aggregationChanged: {},
+ /**
+ * @ngdoc event
+ * @eventOf ui.grid.grouping.api:PublicApi
+ * @name groupingChanged
+ * @description raised whenever the grouped columns changes
+ *
+ *
+ * gridApi.grouping.on.groupingChanged(scope,function(col){})
+ *
+ * @param {GridColumn} col the column which on which grouping changed. The new grouping is
+ * available as `col.grouping`
+ */
+ groupingChanged: {}
+ }
+ },
+ methods: {
+ grouping: {
+ /**
+ * @ngdoc function
+ * @name getGrouping
+ * @methodOf ui.grid.grouping.api:PublicApi
+ * @description Get the grouping configuration for this grid,
+ * used by the saveState feature. Adds expandedState to the information
+ * provided by the internal getGrouping, and removes any aggregations that have a source
+ * of grouping (i.e. will be automatically reapplied when we regroup the column)
+ * Returned grouping is an object
+ * `{ grouping: groupArray, treeAggregations: aggregateArray, expandedState: hash }`
+ * where grouping contains an array of objects:
+ * `{ field: column.field, colName: column.name, groupPriority: column.grouping.groupPriority }`
+ * and aggregations contains an array of objects:
+ * `{ field: column.field, colName: column.name, aggregation: column.grouping.aggregation }`
+ * and expandedState is a hash of the currently expanded nodes
+ *
+ * The groupArray will be sorted by groupPriority.
+ *
+ * @param {boolean} getExpanded whether or not to return the expanded state
+ * @returns {object} grouping configuration
+ */
+ getGrouping: function ( getExpanded ) {
+ var grouping = service.getGrouping(grid);
+
+ grouping.grouping.forEach( function( group ) {
+ group.colName = group.col.name;
+ delete group.col;
+ });
+
+ grouping.aggregations.forEach( function( aggregation ) {
+ aggregation.colName = aggregation.col.name;
+ delete aggregation.col;
+ });
+
+ grouping.aggregations = grouping.aggregations.filter( function( aggregation ){
+ return !aggregation.aggregation.source || aggregation.aggregation.source !== 'grouping';
+ });
+
+ if ( getExpanded ){
+ grouping.rowExpandedStates = service.getRowExpandedStates( grid.grouping.groupingHeaderCache );
+ }
+
+ return grouping;
+ },
+
+ /**
+ * @ngdoc function
+ * @name setGrouping
+ * @methodOf ui.grid.grouping.api:PublicApi
+ * @description Set the grouping configuration for this grid,
+ * used by the saveState feature, but can also be used by any
+ * user to specify a combined grouping and aggregation configuration
+ * @param {object} config the config you want to apply, in the format
+ * provided out by getGrouping
+ */
+ setGrouping: function ( config ) {
+ service.setGrouping(grid, config);
+ },
+
+ /**
+ * @ngdoc function
+ * @name groupColumn
+ * @methodOf ui.grid.grouping.api:PublicApi
+ * @description Adds this column to the existing grouping, at the end of the priority order.
+ * If the column doesn't have a sort, adds one, by default ASC
+ *
+ * This column will move to the left of any non-group columns, the
+ * move is handled in a columnProcessor, so gets called as part of refresh
+ *
+ * @param {string} columnName the name of the column we want to group
+ */
+ groupColumn: function( columnName ) {
+ var column = grid.getColumn(columnName);
+ service.groupColumn(grid, column);
+ },
+
+ /**
+ * @ngdoc function
+ * @name ungroupColumn
+ * @methodOf ui.grid.grouping.api:PublicApi
+ * @description Removes the groupPriority from this column. If the
+ * column was previously aggregated the aggregation will come back.
+ * The sort will remain.
+ *
+ * This column will move to the right of any other group columns, the
+ * move is handled in a columnProcessor, so gets called as part of refresh
+ *
+ * @param {string} columnName the name of the column we want to ungroup
+ */
+ ungroupColumn: function( columnName ) {
+ var column = grid.getColumn(columnName);
+ service.ungroupColumn(grid, column);
+ },
+
+ /**
+ * @ngdoc function
+ * @name clearGrouping
+ * @methodOf ui.grid.grouping.api:PublicApi
+ * @description Clear any grouped columns and any aggregations. Doesn't remove sorting,
+ * as we don't know whether that sorting was added by grouping or was there beforehand
+ *
+ */
+ clearGrouping: function() {
+ service.clearGrouping(grid);
+ },
+
+ /**
+ * @ngdoc function
+ * @name aggregateColumn
+ * @methodOf ui.grid.grouping.api:PublicApi
+ * @description Sets the aggregation type on a column, if the
+ * column is currently grouped then it removes the grouping first.
+ * If the aggregationDef is null then will result in the aggregation
+ * being removed
+ *
+ * @param {string} columnName the column we want to aggregate
+ * @param {string} or {function} aggregationDef one of the recognised types
+ * from uiGridGroupingConstants or a custom aggregation function.
+ * @param {string} aggregationLabel (optional) The label to use for this aggregation.
+ */
+ aggregateColumn: function( columnName, aggregationDef, aggregationLabel){
+ var column = grid.getColumn(columnName);
+ service.aggregateColumn( grid, column, aggregationDef, aggregationLabel);
+ }
+
+ }
+ }
+ };
+
+ grid.api.registerEventsFromObject(publicApi.events);
+
+ grid.api.registerMethodsFromObject(publicApi.methods);
+
+ grid.api.core.on.sortChanged( $scope, service.tidyPriorities);
+
+ },
+
+ defaultGridOptions: function (gridOptions) {
+ //default option to true unless it was explicitly set to false
+ /**
+ * @ngdoc object
+ * @name ui.grid.grouping.api:GridOptions
+ *
+ * @description GridOptions for grouping feature, these are available to be
+ * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
+ */
+
+ /**
+ * @ngdoc object
+ * @name enableGrouping
+ * @propertyOf ui.grid.grouping.api:GridOptions
+ * @description Enable row grouping for entire grid.
+ *
Defaults to true
+ */
+ gridOptions.enableGrouping = gridOptions.enableGrouping !== false;
+
+ /**
+ * @ngdoc object
+ * @name groupingShowCounts
+ * @propertyOf ui.grid.grouping.api:GridOptions
+ * @description shows counts on the groupHeader rows. Not that if you are using a cellFilter or a
+ * sortingAlgorithm which relies on a specific format or data type, showing counts may cause that
+ * to break, since the group header rows will always be a string with groupingShowCounts enabled.
+ *
Defaults to true except on columns of types 'date' and 'object'
+ */
+ gridOptions.groupingShowCounts = gridOptions.groupingShowCounts !== false;
+
+ /**
+ * @ngdoc object
+ * @name groupingNullLabel
+ * @propertyOf ui.grid.grouping.api:GridOptions
+ * @description The string to use for the grouping header row label on rows which contain a null or undefined value in the grouped column.
+ *
Defaults to "Null"
+ */
+ gridOptions.groupingNullLabel = typeof(gridOptions.groupingNullLabel) === 'undefined' ? 'Null' : gridOptions.groupingNullLabel;
+
+ /**
+ * @ngdoc object
+ * @name enableGroupHeaderSelection
+ * @propertyOf ui.grid.grouping.api:GridOptions
+ * @description Allows group header rows to be selected.
+ *
Defaults to false
+ */
+ gridOptions.enableGroupHeaderSelection = gridOptions.enableGroupHeaderSelection === true;
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name groupingColumnBuilder
+ * @methodOf ui.grid.grouping.service:uiGridGroupingService
+ * @description Sets the grouping defaults based on the columnDefs
+ *
+ * @param {object} colDef columnDef we're basing on
+ * @param {GridColumn} col the column we're to update
+ * @param {object} gridOptions the options we should use
+ * @returns {promise} promise for the builder - actually we do it all inline so it's immediately resolved
+ */
+ groupingColumnBuilder: function (colDef, col, gridOptions) {
+ /**
+ * @ngdoc object
+ * @name ui.grid.grouping.api:ColumnDef
+ *
+ * @description ColumnDef for grouping feature, these are available to be
+ * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
+ */
+
+ /**
+ * @ngdoc object
+ * @name enableGrouping
+ * @propertyOf ui.grid.grouping.api:ColumnDef
+ * @description Enable grouping on this column
+ *
Defaults to true.
+ */
+ if (colDef.enableGrouping === false){
+ return;
+ }
+
+ /**
+ * @ngdoc object
+ * @name grouping
+ * @propertyOf ui.grid.grouping.api:ColumnDef
+ * @description Set the grouping for a column. Format is:
+ * ```
+ * {
+ * groupPriority:
Defaults to undefined.
+ */
+
+ if ( typeof(col.grouping) === 'undefined' && typeof(colDef.grouping) !== 'undefined') {
+ col.grouping = angular.copy(colDef.grouping);
+ if ( typeof(col.grouping.groupPriority) !== 'undefined' && col.grouping.groupPriority > -1 ){
+ col.treeAggregationFn = uiGridTreeBaseService.nativeAggregations()[uiGridGroupingConstants.aggregation.COUNT].aggregationFn;
+ col.treeAggregationFinalizerFn = service.groupedFinalizerFn;
+ }
+ } else if (typeof(col.grouping) === 'undefined'){
+ col.grouping = {};
+ }
+
+ if (typeof(col.grouping) !== 'undefined' && typeof(col.grouping.groupPriority) !== 'undefined' && col.grouping.groupPriority >= 0){
+ col.suppressRemoveSort = true;
+ }
+
+ var groupColumn = {
+ name: 'ui.grid.grouping.group',
+ title: i18nService.get().grouping.group,
+ icon: 'ui-grid-icon-indent-right',
+ shown: function () {
+ return typeof(this.context.col.grouping) === 'undefined' ||
+ typeof(this.context.col.grouping.groupPriority) === 'undefined' ||
+ this.context.col.grouping.groupPriority < 0;
+ },
+ action: function () {
+ service.groupColumn( this.context.col.grid, this.context.col );
+ }
+ };
+
+ var ungroupColumn = {
+ name: 'ui.grid.grouping.ungroup',
+ title: i18nService.get().grouping.ungroup,
+ icon: 'ui-grid-icon-indent-left',
+ shown: function () {
+ return typeof(this.context.col.grouping) !== 'undefined' &&
+ typeof(this.context.col.grouping.groupPriority) !== 'undefined' &&
+ this.context.col.grouping.groupPriority >= 0;
+ },
+ action: function () {
+ service.ungroupColumn( this.context.col.grid, this.context.col );
+ }
+ };
+
+ var aggregateRemove = {
+ name: 'ui.grid.grouping.aggregateRemove',
+ title: i18nService.get().grouping.aggregate_remove,
+ shown: function () {
+ return typeof(this.context.col.treeAggregationFn) !== 'undefined';
+ },
+ action: function () {
+ service.aggregateColumn( this.context.col.grid, this.context.col, null);
+ }
+ };
+
+ // generic adder for the aggregation menus, which follow a pattern
+ var addAggregationMenu = function(type, title){
+ title = title || i18nService.get().grouping['aggregate_' + type] || type;
+ var menuItem = {
+ name: 'ui.grid.grouping.aggregate' + type,
+ title: title,
+ shown: function () {
+ return typeof(this.context.col.treeAggregation) === 'undefined' ||
+ typeof(this.context.col.treeAggregation.type) === 'undefined' ||
+ this.context.col.treeAggregation.type !== type;
+ },
+ action: function () {
+ service.aggregateColumn( this.context.col.grid, this.context.col, type);
+ }
+ };
+
+ if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.aggregate' + type)) {
+ col.menuItems.push(menuItem);
+ }
+ };
+
+ /**
+ * @ngdoc object
+ * @name groupingShowGroupingMenu
+ * @propertyOf ui.grid.grouping.api:ColumnDef
+ * @description Show the grouping (group and ungroup items) menu on this column
+ *
Defaults to true.
+ */
+ if ( col.colDef.groupingShowGroupingMenu !== false ){
+ if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.group')) {
+ col.menuItems.push(groupColumn);
+ }
+
+ if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.ungroup')) {
+ col.menuItems.push(ungroupColumn);
+ }
+ }
+
+
+ /**
+ * @ngdoc object
+ * @name groupingShowAggregationMenu
+ * @propertyOf ui.grid.grouping.api:ColumnDef
+ * @description Show the aggregation menu on this column
+ *
Defaults to true.
+ */
+ if ( col.colDef.groupingShowAggregationMenu !== false ){
+ angular.forEach(uiGridTreeBaseService.nativeAggregations(), function(aggregationDef, name){
+ addAggregationMenu(name);
+ });
+ angular.forEach(gridOptions.treeCustomAggregations, function(aggregationDef, name){
+ addAggregationMenu(name, aggregationDef.menuTitle);
+ });
+
+ if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.grouping.aggregateRemove')) {
+ col.menuItems.push(aggregateRemove);
+ }
+ }
+ },
+
+
+
+
+ /**
+ * @ngdoc function
+ * @name groupingColumnProcessor
+ * @methodOf ui.grid.grouping.service:uiGridGroupingService
+ * @description Moves the columns around based on which are grouped
+ *
+ * @param {array} columns the columns to consider rendering
+ * @param {array} rows the grid rows, which we don't use but are passed to us
+ * @returns {array} updated columns array
+ */
+ groupingColumnProcessor: function( columns, rows ) {
+ var grid = this;
+
+ columns = service.moveGroupColumns(this, columns, rows);
+ return columns;
+ },
+
+ /**
+ * @ngdoc function
+ * @name groupedFinalizerFn
+ * @methodOf ui.grid.grouping.service:uiGridGroupingService
+ * @description Used on group columns to display the rendered value and optionally
+ * display the count of rows.
+ *
+ * @param {aggregation} the aggregation entity for a grouped column
+ */
+ groupedFinalizerFn: function( aggregation ){
+ var col = this;
+
+ if ( typeof(aggregation.groupVal) !== 'undefined') {
+ aggregation.rendered = aggregation.groupVal;
+ if ( col.grid.options.groupingShowCounts && col.colDef.type !== 'date' && col.colDef.type !== 'object' ){
+ aggregation.rendered += (' (' + aggregation.value + ')');
+ }
+ } else {
+ aggregation.rendered = null;
+ }
+ },
+
+ /**
+ * @ngdoc function
+ * @name moveGroupColumns
+ * @methodOf ui.grid.grouping.service:uiGridGroupingService
+ * @description Moves the column order so that the grouped columns are lined up
+ * to the left (well, unless you're RTL, then it's the right). By doing this in
+ * the columnsProcessor, we make it transient - when the column is ungrouped it'll
+ * go back to where it was.
+ *
+ * Does nothing if the option `moveGroupColumns` is set to false.
+ *
+ * @param {Grid} grid grid object
+ * @param {array} columns the columns that we should process/move
+ * @param {array} rows the grid rows
+ * @returns {array} updated columns
+ */
+ moveGroupColumns: function( grid, columns, rows ){
+ if ( grid.options.moveGroupColumns === false){
+ return columns;
+ }
+
+ columns.forEach( function(column, index){
+ // position used to make stable sort in moveGroupColumns
+ column.groupingPosition = index;
+ });
+
+ columns.sort(function(a, b){
+ var a_group, b_group;
+ if (a.isRowHeader){
+ a_group = a.headerPriority;
+ }
+ else if ( typeof(a.grouping) === 'undefined' || typeof(a.grouping.groupPriority) === 'undefined' || a.grouping.groupPriority < 0){
+ a_group = null;
+ } else {
+ a_group = a.grouping.groupPriority;
+ }
+
+ if (b.isRowHeader){
+ b_group = b.headerPriority;
+ }
+ else if ( typeof(b.grouping) === 'undefined' || typeof(b.grouping.groupPriority) === 'undefined' || b.grouping.groupPriority < 0){
+ b_group = null;
+ } else {
+ b_group = b.grouping.groupPriority;
+ }
+
+ // groups get sorted to the top
+ if ( a_group !== null && b_group === null) { return -1; }
+ if ( b_group !== null && a_group === null) { return 1; }
+ if ( a_group !== null && b_group !== null) {return a_group - b_group; }
+
+ return a.groupingPosition - b.groupingPosition;
+ });
+
+ columns.forEach( function(column, index) {
+ delete column.groupingPosition;
+ });
+
+ return columns;
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name groupColumn
+ * @methodOf ui.grid.grouping.service:uiGridGroupingService
+ * @description Adds this column to the existing grouping, at the end of the priority order.
+ * If the column doesn't have a sort, adds one, by default ASC
+ *
+ * This column will move to the left of any non-group columns, the
+ * move is handled in a columnProcessor, so gets called as part of refresh
+ *
+ * @param {Grid} grid grid object
+ * @param {GridColumn} column the column we want to group
+ */
+ groupColumn: function( grid, column){
+ if ( typeof(column.grouping) === 'undefined' ){
+ column.grouping = {};
+ }
+
+ // set the group priority to the next number in the hierarchy
+ var existingGrouping = service.getGrouping( grid );
+ column.grouping.groupPriority = existingGrouping.grouping.length;
+
+ // save sort in order to restore it when column is ungrouped
+ column.previousSort = angular.copy(column.sort);
+
+ // add sort if not present
+ if ( !column.sort ){
+ column.sort = { direction: uiGridConstants.ASC };
+ } else if ( typeof(column.sort.direction) === 'undefined' || column.sort.direction === null ){
+ column.sort.direction = uiGridConstants.ASC;
+ }
+
+ column.treeAggregation = { type: uiGridGroupingConstants.aggregation.COUNT, source: 'grouping' };
+ column.treeAggregationFn = uiGridTreeBaseService.nativeAggregations()[uiGridGroupingConstants.aggregation.COUNT].aggregationFn;
+ column.treeAggregationFinalizerFn = service.groupedFinalizerFn;
+
+ grid.api.grouping.raise.groupingChanged(column);
+ // This indirectly calls service.tidyPriorities( grid );
+ grid.api.core.raise.sortChanged(grid, grid.getColumnSorting());
+
+ grid.queueGridRefresh();
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name ungroupColumn
+ * @methodOf ui.grid.grouping.service:uiGridGroupingService
+ * @description Removes the groupPriority from this column. If the
+ * column was previously aggregated the aggregation will come back.
+ * The sort will remain.
+ *
+ * This column will move to the right of any other group columns, the
+ * move is handled in a columnProcessor, so gets called as part of refresh
+ *
+ * @param {Grid} grid grid object
+ * @param {GridColumn} column the column we want to ungroup
+ */
+ ungroupColumn: function( grid, column){
+ if ( typeof(column.grouping) === 'undefined' ){
+ return;
+ }
+
+ delete column.grouping.groupPriority;
+ delete column.treeAggregation;
+ delete column.customTreeAggregationFinalizer;
+
+ if (column.previousSort) {
+ column.sort = column.previousSort;
+ delete column.previousSort;
+ }
+
+ service.tidyPriorities( grid );
+
+ grid.api.grouping.raise.groupingChanged(column);
+ grid.api.core.raise.sortChanged(grid, grid.getColumnSorting());
+
+ grid.queueGridRefresh();
+ },
+
+ /**
+ * @ngdoc function
+ * @name aggregateColumn
+ * @methodOf ui.grid.grouping.service:uiGridGroupingService
+ * @description Sets the aggregation type on a column, if the
+ * column is currently grouped then it removes the grouping first.
+ *
+ * @param {Grid} grid grid object
+ * @param {GridColumn} column the column we want to aggregate
+ * @param {string} aggregationType of the recognised types from uiGridGroupingConstants or one of the custom aggregations from gridOptions
+ */
+ aggregateColumn: function( grid, column, aggregationType){
+
+ if (typeof(column.grouping) !== 'undefined' && typeof(column.grouping.groupPriority) !== 'undefined' && column.grouping.groupPriority >= 0){
+ service.ungroupColumn( grid, column );
+ }
+
+ var aggregationDef = {};
+ if ( typeof(grid.options.treeCustomAggregations[aggregationType]) !== 'undefined' ){
+ aggregationDef = grid.options.treeCustomAggregations[aggregationType];
+ } else if ( typeof(uiGridTreeBaseService.nativeAggregations()[aggregationType]) !== 'undefined' ){
+ aggregationDef = uiGridTreeBaseService.nativeAggregations()[aggregationType];
+ }
+
+ column.treeAggregation = { type: aggregationType, label: i18nService.get().aggregation[aggregationDef.label] || aggregationDef.label };
+ column.treeAggregationFn = aggregationDef.aggregationFn;
+ column.treeAggregationFinalizerFn = aggregationDef.finalizerFn;
+
+ grid.api.grouping.raise.aggregationChanged(column);
+
+ grid.queueGridRefresh();
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name setGrouping
+ * @methodOf ui.grid.grouping.service:uiGridGroupingService
+ * @description Set the grouping based on a config object, used by the save state feature
+ * (more specifically, by the restore function in that feature )
+ *
+ * @param {Grid} grid grid object
+ * @param {object} config the config we want to set, same format as that returned by getGrouping
+ */
+ setGrouping: function ( grid, config ){
+ if ( typeof(config) === 'undefined' ){
+ return;
+ }
+
+ // first remove any existing grouping
+ service.clearGrouping(grid);
+
+ if ( config.grouping && config.grouping.length && config.grouping.length > 0 ){
+ config.grouping.forEach( function( group ) {
+ var col = grid.getColumn(group.colName);
+
+ if ( col ) {
+ service.groupColumn( grid, col );
+ }
+ });
+ }
+
+ if ( config.aggregations && config.aggregations.length ){
+ config.aggregations.forEach( function( aggregation ) {
+ var col = grid.getColumn(aggregation.colName);
+
+ if ( col ) {
+ service.aggregateColumn( grid, col, aggregation.aggregation.type );
+ }
+ });
+ }
+
+ if ( config.rowExpandedStates ){
+ service.applyRowExpandedStates( grid.grouping.groupingHeaderCache, config.rowExpandedStates );
+ }
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name clearGrouping
+ * @methodOf ui.grid.grouping.service:uiGridGroupingService
+ * @description Clear any grouped columns and any aggregations. Doesn't remove sorting,
+ * as we don't know whether that sorting was added by grouping or was there beforehand
+ *
+ * @param {Grid} grid grid object
+ */
+ clearGrouping: function( grid ) {
+ var currentGrouping = service.getGrouping(grid);
+
+ if ( currentGrouping.grouping.length > 0 ){
+ currentGrouping.grouping.forEach( function( group ) {
+ if (!group.col){
+ // should have a group.colName if there's no col
+ group.col = grid.getColumn(group.colName);
+ }
+ service.ungroupColumn(grid, group.col);
+ });
+ }
+
+ if ( currentGrouping.aggregations.length > 0 ){
+ currentGrouping.aggregations.forEach( function( aggregation ){
+ if (!aggregation.col){
+ // should have a group.colName if there's no col
+ aggregation.col = grid.getColumn(aggregation.colName);
+ }
+ service.aggregateColumn(grid, aggregation.col, null);
+ });
+ }
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name tidyPriorities
+ * @methodOf ui.grid.grouping.service:uiGridGroupingService
+ * @description Renumbers groupPriority and sortPriority such that
+ * groupPriority is contiguous, and sortPriority either matches
+ * groupPriority (for group columns), and otherwise is contiguous and
+ * higher than groupPriority.
+ *
+ * @param {Grid} grid grid object
+ */
+ tidyPriorities: function( grid ){
+ // if we're called from sortChanged, grid is in this, not passed as param, the param can be a column or undefined
+ if ( ( typeof(grid) === 'undefined' || typeof(grid.grid) !== 'undefined' ) && typeof(this.grid) !== 'undefined' ) {
+ grid = this.grid;
+ }
+
+ var groupArray = [];
+ var sortArray = [];
+
+ grid.columns.forEach( function(column, index){
+ if ( typeof(column.grouping) !== 'undefined' && typeof(column.grouping.groupPriority) !== 'undefined' && column.grouping.groupPriority >= 0){
+ groupArray.push(column);
+ } else if ( typeof(column.sort) !== 'undefined' && typeof(column.sort.priority) !== 'undefined' && column.sort.priority >= 0){
+ sortArray.push(column);
+ }
+ });
+
+ groupArray.sort(function(a, b){ return a.grouping.groupPriority - b.grouping.groupPriority; });
+ groupArray.forEach( function(column, index){
+ column.grouping.groupPriority = index;
+ column.suppressRemoveSort = true;
+ if ( typeof(column.sort) === 'undefined'){
+ column.sort = {};
+ }
+ column.sort.priority = index;
+ });
+
+ var i = groupArray.length;
+ sortArray.sort(function(a, b){ return a.sort.priority - b.sort.priority; });
+ sortArray.forEach( function(column, index){
+ column.sort.priority = i;
+ column.suppressRemoveSort = column.colDef.suppressRemoveSort;
+ i++;
+ });
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name groupRows
+ * @methodOf ui.grid.grouping.service:uiGridGroupingService
+ * @description The rowProcessor that creates the groupHeaders (i.e. does
+ * the actual grouping).
+ *
+ * Assumes it is always called after the sorting processor, guaranteed by the priority setting
+ *
+ * Processes all the rows in order, inserting a groupHeader row whenever there is a change
+ * in value of a grouped row, based on the sortAlgorithm used for the column. The group header row
+ * is looked up in the groupHeaderCache, and used from there if there is one. The entity is reset
+ * to {} if one is found.
+ *
+ * As it processes it maintains a `processingState` array. This records, for each level of grouping we're
+ * working with, the following information:
+ * ```
+ * {
+ * fieldName: name,
+ * col: col,
+ * initialised: boolean,
+ * currentValue: value,
+ * currentRow: gridRow,
+ * }
+ * ```
+ * We look for changes in the currentValue at any of the levels. Where we find a change we:
+ *
+ * - create a new groupHeader row in the array
+ *
+ * @param {array} renderableRows the rows we want to process, usually the output from the previous rowProcessor
+ * @returns {array} the updated rows, including our new group rows
+ */
+ groupRows: function( renderableRows ) {
+ if (renderableRows.length === 0){
+ return renderableRows;
+ }
+
+ var grid = this;
+ grid.grouping.oldGroupingHeaderCache = grid.grouping.groupingHeaderCache || {};
+ grid.grouping.groupingHeaderCache = {};
+
+ var processingState = service.initialiseProcessingState( grid );
+
+ // processes each of the fields we are grouping by, checks if the value has changed and inserts a groupHeader
+ // Broken out as shouldn't create functions in a loop.
+ var updateProcessingState = function( groupFieldState, stateIndex ) {
+ var fieldValue = grid.getCellValue(row, groupFieldState.col);
+
+ // look for change of value - and insert a header
+ if ( !groupFieldState.initialised || rowSorter.getSortFn(grid, groupFieldState.col, renderableRows)(fieldValue, groupFieldState.currentValue) !== 0 ){
+ service.insertGroupHeader( grid, renderableRows, i, processingState, stateIndex );
+ i++;
+ }
+ };
+
+ // use a for loop because it's tolerant of the array length changing whilst we go - we can
+ // manipulate the iterator when we insert groupHeader rows
+ for (var i = 0; i < renderableRows.length; i++ ){
+ var row = renderableRows[i];
+
+ if ( row.visible ){
+ processingState.forEach( updateProcessingState );
+ }
+ }
+
+ delete grid.grouping.oldGroupingHeaderCache;
+ return renderableRows;
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name initialiseProcessingState
+ * @methodOf ui.grid.grouping.service:uiGridGroupingService
+ * @description Creates the processing state array that is used
+ * for groupRows.
+ *
+ * @param {Grid} grid grid object
+ * @returns {array} an array in the format described in the groupRows method,
+ * initialised with blank values
+ */
+ initialiseProcessingState: function( grid ){
+ var processingState = [];
+ var columnSettings = service.getGrouping( grid );
+
+ columnSettings.grouping.forEach( function( groupItem, index){
+ processingState.push({
+ fieldName: groupItem.field,
+ col: groupItem.col,
+ initialised: false,
+ currentValue: null,
+ currentRow: null
+ });
+ });
+
+ return processingState;
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name getGrouping
+ * @methodOf ui.grid.grouping.service:uiGridGroupingService
+ * @description Get the grouping settings from the columns. As a side effect
+ * this always renumbers the grouping starting at 0
+ * @param {Grid} grid grid object
+ * @returns {array} an array of the group fields, in order of priority
+ */
+ getGrouping: function( grid ){
+ var groupArray = [];
+ var aggregateArray = [];
+
+ // get all the grouping
+ grid.columns.forEach( function(column, columnIndex){
+ if ( column.grouping ){
+ if ( typeof(column.grouping.groupPriority) !== 'undefined' && column.grouping.groupPriority >= 0){
+ groupArray.push({ field: column.field, col: column, groupPriority: column.grouping.groupPriority, grouping: column.grouping });
+ }
+ }
+ if ( column.treeAggregation && column.treeAggregation.type ){
+ aggregateArray.push({ field: column.field, col: column, aggregation: column.treeAggregation });
+ }
+ });
+
+ // sort grouping into priority order
+ groupArray.sort( function(a, b){
+ return a.groupPriority - b.groupPriority;
+ });
+
+ // renumber the priority in case it was somewhat messed up, then remove the grouping reference
+ groupArray.forEach( function( group, index) {
+ group.grouping.groupPriority = index;
+ group.groupPriority = index;
+ delete group.grouping;
+ });
+
+ return { grouping: groupArray, aggregations: aggregateArray };
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name insertGroupHeader
+ * @methodOf ui.grid.grouping.service:uiGridGroupingService
+ * @description Create a group header row, and link it to the various configuration
+ * items that we use.
+ *
+ * Look for the row in the oldGroupingHeaderCache, write the row into the new groupingHeaderCache.
+ *
+ * @param {Grid} grid grid object
+ * @param {array} renderableRows the rows that we are processing
+ * @param {number} rowIndex the row we were up to processing
+ * @param {array} processingState the current processing state
+ * @param {number} stateIndex the processing state item that we were on when we triggered a new group header -
+ * i.e. the column that we want to create a header for
+ */
+ insertGroupHeader: function( grid, renderableRows, rowIndex, processingState, stateIndex ) {
+ // set the value that caused the end of a group into the header row and the processing state
+ var fieldName = processingState[stateIndex].fieldName;
+ var col = processingState[stateIndex].col;
+
+ var newValue = grid.getCellValue(renderableRows[rowIndex], col);
+ var newDisplayValue = newValue;
+ if ( typeof(newValue) === 'undefined' || newValue === null ) {
+ newDisplayValue = grid.options.groupingNullLabel;
+ }
+
+ var getKeyAsValueForCacheMap = function(key) {
+ if (angular.isObject(key)) {
+ return JSON.stringify(key);
+ } else {
+ return key;
+ }
+ };
+
+ var cacheItem = grid.grouping.oldGroupingHeaderCache;
+ for ( var i = 0; i < stateIndex; i++ ){
+ if ( cacheItem && cacheItem[getKeyAsValueForCacheMap(processingState[i].currentValue)] ){
+ cacheItem = cacheItem[getKeyAsValueForCacheMap(processingState[i].currentValue)].children;
+ }
+ }
+
+ var headerRow;
+ if ( cacheItem && cacheItem[getKeyAsValueForCacheMap(newValue)]){
+ headerRow = cacheItem[getKeyAsValueForCacheMap(newValue)].row;
+ headerRow.entity = {};
+ } else {
+ headerRow = new GridRow( {}, null, grid );
+ gridClassFactory.rowTemplateAssigner.call(grid, headerRow);
+ }
+
+ headerRow.entity['$$' + processingState[stateIndex].col.uid] = { groupVal: newDisplayValue };
+ headerRow.treeLevel = stateIndex;
+ headerRow.groupHeader = true;
+ headerRow.internalRow = true;
+ headerRow.enableCellEdit = false;
+ headerRow.enableSelection = grid.options.enableGroupHeaderSelection;
+ processingState[stateIndex].initialised = true;
+ processingState[stateIndex].currentValue = newValue;
+ processingState[stateIndex].currentRow = headerRow;
+
+ // set all processing states below this one to not be initialised - change of this state
+ // means all those need to start again
+ service.finaliseProcessingState( processingState, stateIndex + 1);
+
+ // insert our new header row
+ renderableRows.splice(rowIndex, 0, headerRow);
+
+ // add our new header row to the cache
+ cacheItem = grid.grouping.groupingHeaderCache;
+ for ( i = 0; i < stateIndex; i++ ){
+ cacheItem = cacheItem[getKeyAsValueForCacheMap(processingState[i].currentValue)].children;
+ }
+ cacheItem[getKeyAsValueForCacheMap(newValue)] = { row: headerRow, children: {} };
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name finaliseProcessingState
+ * @methodOf ui.grid.grouping.service:uiGridGroupingService
+ * @description Set all processing states lower than the one that had a break in value to
+ * no longer be initialised. Render the counts into the entity ready for display.
+ *
+ * @param {array} processingState the current processing state
+ * @param {number} stateIndex the processing state item that we were on when we triggered a new group header, all
+ * processing states after this need to be finalised
+ */
+ finaliseProcessingState: function( processingState, stateIndex ){
+ for ( var i = stateIndex; i < processingState.length; i++){
+ processingState[i].initialised = false;
+ processingState[i].currentRow = null;
+ processingState[i].currentValue = null;
+ }
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name getRowExpandedStates
+ * @methodOf ui.grid.grouping.service:uiGridGroupingService
+ * @description Extract the groupHeaderCache hash, pulling out only the states.
+ *
+ * The example below shows a grid that is grouped by gender then age
+ *
+ *
+ * {
+ * male: {
+ * state: 'expanded',
+ * children: {
+ * 22: { state: 'expanded' },
+ * 30: { state: 'collapsed' }
+ * }
+ * },
+ * female: {
+ * state: 'expanded',
+ * children: {
+ * 28: { state: 'expanded' },
+ * 55: { state: 'collapsed' }
+ * }
+ * }
+ * }
+ *
+ *
+ * @param {object} treeChildren The tree children elements object
+ * @returns {object} the expanded states as an object
+ */
+ getRowExpandedStates: function(treeChildren){
+ if ( typeof(treeChildren) === 'undefined' ){
+ return {};
+ }
+
+ var newChildren = {};
+
+ angular.forEach( treeChildren, function( value, key ){
+ newChildren[key] = { state: value.row.treeNode.state };
+ if ( value.children ){
+ newChildren[key].children = service.getRowExpandedStates( value.children );
+ } else {
+ newChildren[key].children = {};
+ }
+ });
+
+ return newChildren;
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name applyRowExpandedStates
+ * @methodOf ui.grid.grouping.service:uiGridGroupingService
+ * @description Take a hash in the format as created by getRowExpandedStates,
+ * and apply it to the grid.grouping.groupHeaderCache.
+ *
+ * Takes a treeSubset, and applies to a treeSubset - so can be called
+ * recursively.
+ *
+ * @param {object} currentNode can be grid.grouping.groupHeaderCache, or any of
+ * the children of that hash
+ * @param {object} expandedStates can be the full expanded states, or children
+ * of that expanded states (which hopefully matches the subset of the groupHeaderCache)
+ */
+ applyRowExpandedStates: function( currentNode, expandedStates ){
+ if ( typeof(expandedStates) === 'undefined' ){
+ return;
+ }
+
+ angular.forEach(expandedStates, function( value, key ) {
+ if ( currentNode[key] ){
+ currentNode[key].row.treeNode.state = value.state;
+
+ if (value.children && currentNode[key].children){
+ service.applyRowExpandedStates( currentNode[key].children, value.children );
+ }
+ }
+ });
+ }
+
+
+ };
+
+ return service;
+
+ }]);
+
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.grouping.directive:uiGridGrouping
+ * @element div
+ * @restrict A
+ *
+ * @description Adds grouping features to grid
+ *
+ * @example
+
+ * gridOptions.importerProcessHeaders: function( grid, headerArray ) {
+ * var myHeaderColumns = [];
+ * var thisCol;
+ * headerArray.forEach( function( value, index ) {
+ * thisCol = mySpecialLookupFunction( value );
+ * myHeaderColumns.push( thisCol.name );
+ * });
+ *
+ * return myHeaderCols;
+ * })
+ *
+ * @param {Grid} grid the grid we're importing into
+ * @param {array} headerArray an array of the text from the first row of the csv file,
+ * which you need to match to column.names
+ * @returns {array} array of matching column names, in the same order as the headerArray
+ *
+ */
+ gridOptions.importerProcessHeaders = gridOptions.importerProcessHeaders || service.processHeaders;
+
+ /**
+ * @ngdoc method
+ * @name importerHeaderFilter
+ * @methodOf ui.grid.importer.api:GridOptions
+ * @description A callback function that will filter (usually translate) a single
+ * header. Used when you want to match the passed in column names to the column
+ * displayName after the header filter.
+ *
+ * Your callback routine needs to return the filtered header value.
+ *
+ * gridOptions.importerHeaderFilter: function( displayName ) {
+ * return $translate.instant( displayName );
+ * })
+ *
+ *
+ * or:
+ *
+ * gridOptions.importerHeaderFilter: $translate.instant
+ *
+ * @param {string} displayName the displayName that we'd like to translate
+ * @returns {string} the translated name
+ *
+ */
+ gridOptions.importerHeaderFilter = gridOptions.importerHeaderFilter || function( displayName ) { return displayName; };
+
+ /**
+ * @ngdoc method
+ * @name importerErrorCallback
+ * @methodOf ui.grid.importer.api:GridOptions
+ * @description A callback function that provides custom error handling, rather
+ * than the standard grid behaviour of an alert box and a console message. You
+ * might use this to internationalise the console log messages, or to write to a
+ * custom logging routine that returned errors to the server.
+ *
+ *
+ * gridOptions.importerErrorCallback: function( grid, errorKey, consoleMessage, context ) {
+ * myUserDisplayRoutine( errorKey );
+ * myLoggingRoutine( consoleMessage, context );
+ * })
+ *
+ * @param {Grid} grid the grid we're importing into, may be useful if you're positioning messages
+ * in some way
+ * @param {string} errorKey one of the i18n keys the importer can return - importer.noHeaders,
+ * importer.noObjects, importer.invalidCsv, importer.invalidJson, importer.jsonNotArray
+ * @param {string} consoleMessage the English console message that importer would have written
+ * @param {object} context the context data that importer would have appended to that console message,
+ * often the file content itself or the element that is in error
+ *
+ */
+ if ( !gridOptions.importerErrorCallback || typeof(gridOptions.importerErrorCallback) !== 'function' ){
+ delete gridOptions.importerErrorCallback;
+ }
+
+ /**
+ * @ngdoc method
+ * @name importerDataAddCallback
+ * @methodOf ui.grid.importer.api:GridOptions
+ * @description A mandatory callback function that adds data to the source data array. The grid
+ * generally doesn't add rows to the source data array, it is tidier to handle this through a user
+ * callback.
+ *
+ *
+ * gridOptions.importerDataAddCallback: function( grid, newObjects ) {
+ * $scope.myData = $scope.myData.concat( newObjects );
+ * })
+ *
+ * @param {Grid} grid the grid we're importing into, may be useful in some way
+ * @param {array} newObjects an array of new objects that you should add to your data
+ *
+ */
+ if ( gridOptions.enableImporter === true && !gridOptions.importerDataAddCallback ) {
+ gridUtil.logError("You have not set an importerDataAddCallback, importer is disabled");
+ gridOptions.enableImporter = false;
+ }
+
+ /**
+ * @ngdoc object
+ * @name importerNewObject
+ * @propertyOf ui.grid.importer.api:GridOptions
+ * @description An object on which we call `new` to create each new row before inserting it into
+ * the data array. Typically this would be a $resource entity, which means that if you're using
+ * the rowEdit feature, you can directly call save on this entity when the save event is triggered.
+ *
+ * Defaults to a vanilla javascript object
+ *
+ * @example
+ *
+ * gridOptions.importerNewObject = MyRes;
+ *
+ *
+ */
+
+ /**
+ * @ngdoc property
+ * @propertyOf ui.grid.importer.api:GridOptions
+ * @name importerShowMenu
+ * @description Whether or not to show an item in the grid menu. Defaults to true.
+ *
+ */
+ gridOptions.importerShowMenu = gridOptions.importerShowMenu !== false;
+
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.importer.api:GridOptions
+ * @name importerObjectCallback
+ * @description A callback that massages the data for each object. For example,
+ * you might have data stored as a code value, but display the decode. This callback
+ * can be used to change the decoded value back into a code. Defaults to doing nothing.
+ * @param {Grid} grid in case you need it
+ * @param {object} newObject the new object as importer has created it, modify it
+ * then return the modified version
+ * @returns {object} the modified object
+ * @example
+ *
+ * gridOptions.importerObjectCallback = function ( grid, newObject ) {
+ * switch newObject.status {
+ * case 'Active':
+ * newObject.status = 1;
+ * break;
+ * case 'Inactive':
+ * newObject.status = 2;
+ * break;
+ * }
+ * return newObject;
+ * };
+ *
+ */
+ gridOptions.importerObjectCallback = gridOptions.importerObjectCallback || function( grid, newObject ) { return newObject; };
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name addToMenu
+ * @methodOf ui.grid.importer.service:uiGridImporterService
+ * @description Adds import menu item to the grid menu,
+ * allowing the user to request import of a file
+ * @param {Grid} grid the grid into which data should be imported
+ */
+ addToMenu: function ( grid ) {
+ grid.api.core.addToGridMenu( grid, [
+ {
+ title: i18nService.getSafeText('gridMenu.importerTitle'),
+ order: 150
+ },
+ {
+ templateUrl: 'ui-grid/importerMenuItemContainer',
+ action: function ($event) {
+ this.grid.api.importer.importAFile( grid );
+ },
+ order: 151
+ }
+ ]);
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name importThisFile
+ * @methodOf ui.grid.importer.service:uiGridImporterService
+ * @description Imports the provided file into the grid using the file object
+ * provided. Bypasses the grid menu
+ * @param {Grid} grid the grid we're importing into
+ * @param {File} fileObject the file we want to import, as returned from the File
+ * javascript object
+ */
+ importThisFile: function ( grid, fileObject ) {
+ if (!fileObject){
+ gridUtil.logError( 'No file object provided to importThisFile, should be impossible, aborting');
+ return;
+ }
+
+ var reader = new FileReader();
+
+ switch ( fileObject.type ){
+ case 'application/json':
+ reader.onload = service.importJsonClosure( grid );
+ break;
+ default:
+ reader.onload = service.importCsvClosure( grid );
+ break;
+ }
+
+ reader.readAsText( fileObject );
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name importJson
+ * @methodOf ui.grid.importer.service:uiGridImporterService
+ * @description Creates a function that imports a json file into the grid.
+ * The json data is imported into new objects of type `gridOptions.importerNewObject`,
+ * and if the rowEdit feature is enabled the rows are marked as dirty
+ * @param {Grid} grid the grid we want to import into
+ * @param {FileObject} importFile the file that we want to import, as
+ * a FileObject
+ */
+ importJsonClosure: function( grid ) {
+ return function( importFile ){
+ var newObjects = [];
+ var newObject;
+
+ var importArray = service.parseJson( grid, importFile );
+ if (importArray === null){
+ return;
+ }
+ importArray.forEach( function( value, index ) {
+ newObject = service.newObject( grid );
+ angular.extend( newObject, value );
+ newObject = grid.options.importerObjectCallback( grid, newObject );
+ newObjects.push( newObject );
+ });
+
+ service.addObjects( grid, newObjects );
+
+ };
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name parseJson
+ * @methodOf ui.grid.importer.service:uiGridImporterService
+ * @description Parses a json file, returns the parsed data.
+ * Displays an error if file doesn't parse
+ * @param {Grid} grid the grid that we want to import into
+ * @param {FileObject} importFile the file that we want to import, as
+ * a FileObject
+ * @returns {array} array of objects from the imported json
+ */
+ parseJson: function( grid, importFile ){
+ var loadedObjects;
+ try {
+ loadedObjects = JSON.parse( importFile.target.result );
+ } catch (e) {
+ service.alertError( grid, 'importer.invalidJson', 'File could not be processed, is it valid json? Content was: ', importFile.target.result );
+ return;
+ }
+
+ if ( !Array.isArray( loadedObjects ) ){
+ service.alertError( grid, 'importer.jsonNotarray', 'Import failed, file is not an array, file was: ', importFile.target.result );
+ return [];
+ } else {
+ return loadedObjects;
+ }
+ },
+
+
+
+ /**
+ * @ngdoc function
+ * @name importCsvClosure
+ * @methodOf ui.grid.importer.service:uiGridImporterService
+ * @description Creates a function that imports a csv file into the grid
+ * (allowing it to be used in the reader.onload event)
+ * @param {Grid} grid the grid that we want to import into
+ * @param {FileObject} importFile the file that we want to import, as
+ * a file object
+ */
+ importCsvClosure: function( grid ) {
+ return function( importFile ){
+ var importArray = service.parseCsv( importFile );
+ if ( !importArray || importArray.length < 1 ){
+ service.alertError( grid, 'importer.invalidCsv', 'File could not be processed, is it valid csv? Content was: ', importFile.target.result );
+ return;
+ }
+
+ var newObjects = service.createCsvObjects( grid, importArray );
+ if ( !newObjects || newObjects.length === 0 ){
+ service.alertError( grid, 'importer.noObjects', 'Objects were not able to be derived, content was: ', importFile.target.result );
+ return;
+ }
+
+ service.addObjects( grid, newObjects );
+ };
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name parseCsv
+ * @methodOf ui.grid.importer.service:uiGridImporterService
+ * @description Parses a csv file into an array of arrays, with the first
+ * array being the headers, and the remaining arrays being the data.
+ * The logic for this comes from https://github.com/thetalecrafter/excel.js/blob/master/src/csv.js,
+ * which is noted as being under the MIT license. The code is modified to pass the jscs yoda condition
+ * checker
+ * @param {FileObject} importFile the file that we want to import, as a
+ * file object
+ */
+ parseCsv: function( importFile ) {
+ var csv = importFile.target.result;
+
+ // use the CSV-JS library to parse
+ return CSV.parse(csv);
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name createCsvObjects
+ * @methodOf ui.grid.importer.service:uiGridImporterService
+ * @description Converts an array of arrays (representing the csv file)
+ * into a set of objects. Uses the provided `gridOptions.importerNewObject`
+ * to create the objects, and maps the header row into the individual columns
+ * using either `gridOptions.importerProcessHeaders`, or by using a native method
+ * of matching to either the displayName, column name or column field of
+ * the columns in the column defs. The resulting objects will have attributes
+ * that are named based on the column.field or column.name, in that order.
+ * @param {Grid} grid the grid that we want to import into
+ * @param {Array} importArray the data that we want to import, as an array
+ */
+ createCsvObjects: function( grid, importArray ){
+ // pull off header row and turn into headers
+ var headerMapping = grid.options.importerProcessHeaders( grid, importArray.shift() );
+ if ( !headerMapping || headerMapping.length === 0 ){
+ service.alertError( grid, 'importer.noHeaders', 'Column names could not be derived, content was: ', importArray );
+ return [];
+ }
+
+ var newObjects = [];
+ var newObject;
+ importArray.forEach( function( row, index ) {
+ newObject = service.newObject( grid );
+ if ( row !== null ){
+ row.forEach( function( field, index ){
+ if ( headerMapping[index] !== null ){
+ newObject[ headerMapping[index] ] = field;
+ }
+ });
+ }
+ newObject = grid.options.importerObjectCallback( grid, newObject );
+ newObjects.push( newObject );
+ });
+
+ return newObjects;
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name processHeaders
+ * @methodOf ui.grid.importer.service:uiGridImporterService
+ * @description Determines the columns that the header row from
+ * a csv (or other) file represents.
+ * @param {Grid} grid the grid we're importing into
+ * @param {array} headerRow the header row that we wish to match against
+ * the column definitions
+ * @returns {array} an array of the attribute names that should be used
+ * for that column, based on matching the headers or creating the headers
+ *
+ */
+ processHeaders: function( grid, headerRow ) {
+ var headers = [];
+ if ( !grid.options.columnDefs || grid.options.columnDefs.length === 0 ){
+ // we are going to create new columnDefs for all these columns, so just remove
+ // spaces from the names to create fields
+ headerRow.forEach( function( value, index ) {
+ headers.push( value.replace( /[^0-9a-zA-Z\-_]/g, '_' ) );
+ });
+ return headers;
+ } else {
+ var lookupHash = service.flattenColumnDefs( grid, grid.options.columnDefs );
+ headerRow.forEach( function( value, index ) {
+ if ( lookupHash[value] ) {
+ headers.push( lookupHash[value] );
+ } else if ( lookupHash[ value.toLowerCase() ] ) {
+ headers.push( lookupHash[ value.toLowerCase() ] );
+ } else {
+ headers.push( null );
+ }
+ });
+ return headers;
+ }
+ },
+
+
+ /**
+ * @name flattenColumnDefs
+ * @methodOf ui.grid.importer.service:uiGridImporterService
+ * @description Runs through the column defs and creates a hash of
+ * the displayName, name and field, and of each of those values forced to lower case,
+ * with each pointing to the field or name
+ * (whichever is present). Used to lookup column headers and decide what
+ * attribute name to give to the resulting field.
+ * @param {Grid} grid the grid we're importing into
+ * @param {array} columnDefs the columnDefs that we should flatten
+ * @returns {hash} the flattened version of the column def information, allowing
+ * us to look up a value by `flattenedHash[ headerValue ]`
+ */
+ flattenColumnDefs: function( grid, columnDefs ){
+ var flattenedHash = {};
+ columnDefs.forEach( function( columnDef, index) {
+ if ( columnDef.name ){
+ flattenedHash[ columnDef.name ] = columnDef.field || columnDef.name;
+ flattenedHash[ columnDef.name.toLowerCase() ] = columnDef.field || columnDef.name;
+ }
+
+ if ( columnDef.field ){
+ flattenedHash[ columnDef.field ] = columnDef.field || columnDef.name;
+ flattenedHash[ columnDef.field.toLowerCase() ] = columnDef.field || columnDef.name;
+ }
+
+ if ( columnDef.displayName ){
+ flattenedHash[ columnDef.displayName ] = columnDef.field || columnDef.name;
+ flattenedHash[ columnDef.displayName.toLowerCase() ] = columnDef.field || columnDef.name;
+ }
+
+ if ( columnDef.displayName && grid.options.importerHeaderFilter ){
+ flattenedHash[ grid.options.importerHeaderFilter(columnDef.displayName) ] = columnDef.field || columnDef.name;
+ flattenedHash[ grid.options.importerHeaderFilter(columnDef.displayName).toLowerCase() ] = columnDef.field || columnDef.name;
+ }
+ });
+
+ return flattenedHash;
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name addObjects
+ * @methodOf ui.grid.importer.service:uiGridImporterService
+ * @description Inserts our new objects into the grid data, and
+ * sets the rows to dirty if the rowEdit feature is being used
+ *
+ * Does this by registering a watch on dataChanges, which essentially
+ * is waiting on the result of the grid data watch, and downstream processing.
+ *
+ * When the callback is called, it deregisters itself - we don't want to run
+ * again next time data is added.
+ *
+ * If we never get called, we deregister on destroy.
+ *
+ * @param {Grid} grid the grid we're importing into
+ * @param {array} newObjects the objects we want to insert into the grid data
+ * @returns {object} the new object
+ */
+ addObjects: function( grid, newObjects, $scope ){
+ if ( grid.api.rowEdit ){
+ var dataChangeDereg = grid.registerDataChangeCallback( function() {
+ grid.api.rowEdit.setRowsDirty( newObjects );
+ dataChangeDereg();
+ }, [uiGridConstants.dataChange.ROW] );
+
+ grid.importer.$scope.$on( '$destroy', dataChangeDereg );
+ }
+
+ grid.importer.$scope.$apply( grid.options.importerDataAddCallback( grid, newObjects ) );
+
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name newObject
+ * @methodOf ui.grid.importer.service:uiGridImporterService
+ * @description Makes a new object based on `gridOptions.importerNewObject`,
+ * or based on an empty object if not present
+ * @param {Grid} grid the grid we're importing into
+ * @returns {object} the new object
+ */
+ newObject: function( grid ){
+ if ( typeof(grid.options) !== "undefined" && typeof(grid.options.importerNewObject) !== "undefined" ){
+ return new grid.options.importerNewObject();
+ } else {
+ return {};
+ }
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name alertError
+ * @methodOf ui.grid.importer.service:uiGridImporterService
+ * @description Provides an internationalised user alert for the failure,
+ * and logs a console message including diagnostic content.
+ * Optionally, if the the `gridOptions.importerErrorCallback` routine
+ * is defined, then calls that instead, allowing user specified error routines
+ * @param {Grid} grid the grid we're importing into
+ * @param {array} headerRow the header row that we wish to match against
+ * the column definitions
+ */
+ alertError: function( grid, alertI18nToken, consoleMessage, context ){
+ if ( grid.options.importerErrorCallback ){
+ grid.options.importerErrorCallback( grid, alertI18nToken, consoleMessage, context );
+ } else {
+ $window.alert(i18nService.getSafeText( alertI18nToken ));
+ gridUtil.logError(consoleMessage + context );
+ }
+ }
+ };
+
+ return service;
+
+ }
+ ]);
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.importer.directive:uiGridImporter
+ * @element div
+ * @restrict A
+ *
+ * @description Adds importer features to grid
+ *
+ */
+ module.directive('uiGridImporter', ['uiGridImporterConstants', 'uiGridImporterService', 'gridUtil', '$compile',
+ function (uiGridImporterConstants, uiGridImporterService, gridUtil, $compile) {
+ return {
+ replace: true,
+ priority: 0,
+ require: '^uiGrid',
+ scope: false,
+ link: function ($scope, $elm, $attrs, uiGridCtrl) {
+ uiGridImporterService.initializeGrid($scope, uiGridCtrl.grid);
+ }
+ };
+ }
+ ]);
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.importer.directive:uiGridImporterMenuItem
+ * @element div
+ * @restrict A
+ *
+ * @description Handles the processing from the importer menu item - once a file is
+ * selected
+ *
+ */
+ module.directive('uiGridImporterMenuItem', ['uiGridImporterConstants', 'uiGridImporterService', 'gridUtil', '$compile',
+ function (uiGridImporterConstants, uiGridImporterService, gridUtil, $compile) {
+ return {
+ replace: true,
+ priority: 0,
+ require: '?^uiGrid',
+ scope: false,
+ templateUrl: 'ui-grid/importerMenuItem',
+ link: function ($scope, $elm, $attrs, uiGridCtrl) {
+ var grid;
+
+ function handleFileSelect(event) {
+ var target = event.srcElement || event.target;
+
+ if (target && target.files && target.files.length === 1) {
+ var fileObject = target.files[0];
+
+ // Define grid if the uiGrid controller is present
+ if (typeof(uiGridCtrl) !== 'undefined' && uiGridCtrl) {
+ grid = uiGridCtrl.grid;
+
+ uiGridImporterService.importThisFile( grid, fileObject );
+ target.form.reset();
+ } else {
+ gridUtil.logError('Could not import file because UI Grid was not found.');
+ }
+ }
+ }
+
+ var fileChooser = $elm[0].querySelectorAll('.ui-grid-importer-file-chooser');
+
+ if ( fileChooser.length !== 1 ){
+ gridUtil.logError('Found > 1 or < 1 file choosers within the menu item, error, cannot continue');
+ } else {
+ fileChooser[0].addEventListener('change', handleFileSelect, false);
+ }
+ }
+ };
+ }
+ ]);
+})();
diff --git a/release/4.4.11/ui-grid.importer.min.js b/release/4.4.11/ui-grid.importer.min.js
new file mode 100644
index 000000000..260481f7f
--- /dev/null
+++ b/release/4.4.11/ui-grid.importer.min.js
@@ -0,0 +1,7 @@
+/*!
+ * ui-grid - v4.4.11 - 2018-05-16
+ * Copyright (c) 2018 ; License: MIT
+ */
+
+
+!function(){"use strict";var e=angular.module("ui.grid.importer",["ui.grid"]);e.constant("uiGridImporterConstants",{featureName:"importer"}),e.service("uiGridImporterService",["$q","uiGridConstants","uiGridImporterConstants","gridUtil","$compile","$interval","i18nService","$window",function(e,i,r,n,t,o,a,s){var l={initializeGrid:function(e,r){r.importer={$scope:e},this.defaultGridOptions(r.options);var t={events:{importer:{}},methods:{importer:{importFile:function(e){l.importThisFile(r,e)}}}};r.api.registerEventsFromObject(t.events),r.api.registerMethodsFromObject(t.methods),r.options.enableImporter&&r.options.importerShowMenu&&(r.api.core.addToGridMenu?l.addToMenu(r):o(function(){r.api.core.addToGridMenu&&l.addToMenu(r)},100,1))},defaultGridOptions:function(e){e.enableImporter||void 0===e.enableImporter?s.hasOwnProperty("File")&&s.hasOwnProperty("FileReader")&&s.hasOwnProperty("FileList")&&s.hasOwnProperty("Blob")?e.enableImporter=!0:(n.logError("The File APIs are not fully supported in this browser, grid importer cannot be used."),e.enableImporter=!1):e.enableImporter=!1,e.importerProcessHeaders=e.importerProcessHeaders||l.processHeaders,e.importerHeaderFilter=e.importerHeaderFilter||function(e){return e},e.importerErrorCallback&&"function"==typeof e.importerErrorCallback||delete e.importerErrorCallback,!0!==e.enableImporter||e.importerDataAddCallback||(n.logError("You have not set an importerDataAddCallback, importer is disabled"),e.enableImporter=!1),e.importerShowMenu=!1!==e.importerShowMenu,e.importerObjectCallback=e.importerObjectCallback||function(e,r){return r}},addToMenu:function(r){r.api.core.addToGridMenu(r,[{title:a.getSafeText("gridMenu.importerTitle"),order:150},{templateUrl:"ui-grid/importerMenuItemContainer",action:function(e){this.grid.api.importer.importAFile(r)},order:151}])},importThisFile:function(e,r){if(r){var t=new FileReader;switch(r.type){case"application/json":t.onload=l.importJsonClosure(e);break;default:t.onload=l.importCsvClosure(e)}t.readAsText(r)}else n.logError("No file object provided to importThisFile, should be impossible, aborting")},importJsonClosure:function(i){return function(e){var t,o=[],r=l.parseJson(i,e);null!==r&&(r.forEach(function(e,r){t=l.newObject(i),angular.extend(t,e),t=i.options.importerObjectCallback(i,t),o.push(t)}),l.addObjects(i,o))}},parseJson:function(r,t){var e;try{e=JSON.parse(t.target.result)}catch(e){return void l.alertError(r,"importer.invalidJson","File could not be processed, is it valid json? Content was: ",t.target.result)}return Array.isArray(e)?e:(l.alertError(r,"importer.jsonNotarray","Import failed, file is not an array, file was: ",t.target.result),[])},importCsvClosure:function(o){return function(e){var r=l.parseCsv(e);if(!r||r.length<1)l.alertError(o,"importer.invalidCsv","File could not be processed, is it valid csv? Content was: ",e.target.result);else{var t=l.createCsvObjects(o,r);t&&0!==t.length?l.addObjects(o,t):l.alertError(o,"importer.noObjects","Objects were not able to be derived, content was: ",e.target.result)}}},parseCsv:function(e){var r=e.target.result;return CSV.parse(r)},createCsvObjects:function(t,e){var o=t.options.importerProcessHeaders(t,e.shift());if(!o||0===o.length)return l.alertError(t,"importer.noHeaders","Column names could not be derived, content was: ",e),[];var i,n=[];return e.forEach(function(e,r){i=l.newObject(t),null!==e&&e.forEach(function(e,r){null!==o[r]&&(i[o[r]]=e)}),i=t.options.importerObjectCallback(t,i),n.push(i)}),n},processHeaders:function(e,r){var t=[];if(e.options.columnDefs&&0!==e.options.columnDefs.length){var o=l.flattenColumnDefs(e,e.options.columnDefs);return r.forEach(function(e,r){o[e]?t.push(o[e]):o[e.toLowerCase()]?t.push(o[e.toLowerCase()]):t.push(null)}),t}return r.forEach(function(e,r){t.push(e.replace(/[^0-9a-zA-Z\-_]/g,"_"))}),t},flattenColumnDefs:function(t,e){var o={};return e.forEach(function(e,r){e.name&&(o[e.name]=e.field||e.name,o[e.name.toLowerCase()]=e.field||e.name),e.field&&(o[e.field]=e.field||e.name,o[e.field.toLowerCase()]=e.field||e.name),e.displayName&&(o[e.displayName]=e.field||e.name,o[e.displayName.toLowerCase()]=e.field||e.name),e.displayName&&t.options.importerHeaderFilter&&(o[t.options.importerHeaderFilter(e.displayName)]=e.field||e.name,o[t.options.importerHeaderFilter(e.displayName).toLowerCase()]=e.field||e.name)}),o},addObjects:function(e,r,t){if(e.api.rowEdit){var o=e.registerDataChangeCallback(function(){e.api.rowEdit.setRowsDirty(r),o()},[i.dataChange.ROW]);e.importer.$scope.$on("$destroy",o)}e.importer.$scope.$apply(e.options.importerDataAddCallback(e,r))},newObject:function(e){return void 0!==e.options&&void 0!==e.options.importerNewObject?new e.options.importerNewObject:{}},alertError:function(e,r,t,o){e.options.importerErrorCallback?e.options.importerErrorCallback(e,r,t,o):(s.alert(a.getSafeText(r)),n.logError(t+o))}};return l}]),e.directive("uiGridImporter",["uiGridImporterConstants","uiGridImporterService","gridUtil","$compile",function(e,i,r,t){return{replace:!0,priority:0,require:"^uiGrid",scope:!1,link:function(e,r,t,o){i.initializeGrid(e,o.grid)}}}]),e.directive("uiGridImporterMenuItem",["uiGridImporterConstants","uiGridImporterService","gridUtil","$compile",function(e,a,s,r){return{replace:!0,priority:0,require:"?^uiGrid",scope:!1,templateUrl:"ui-grid/importerMenuItem",link:function(e,r,t,o){var i;var n=r[0].querySelectorAll(".ui-grid-importer-file-chooser");1!==n.length?s.logError("Found > 1 or < 1 file choosers within the menu item, error, cannot continue"):n[0].addEventListener("change",function(e){var r=e.srcElement||e.target;if(r&&r.files&&1===r.files.length){var t=r.files[0];void 0!==o&&o?(i=o.grid,a.importThisFile(i,t),r.form.reset()):s.logError("Could not import file because UI Grid was not found.")}},!1)}}}])}();
\ No newline at end of file
diff --git a/release/4.4.11/ui-grid.infinite-scroll.js b/release/4.4.11/ui-grid.infinite-scroll.js
new file mode 100644
index 000000000..14082ec65
--- /dev/null
+++ b/release/4.4.11/ui-grid.infinite-scroll.js
@@ -0,0 +1,546 @@
+/*!
+ * ui-grid - v4.4.11 - 2018-05-16
+ * Copyright (c) 2018 ; License: MIT
+ */
+
+(function() {
+ 'use strict';
+ /**
+ * @ngdoc overview
+ * @name ui.grid.infiniteScroll
+ *
+ * @description
+ *
+ * #ui.grid.infiniteScroll
+ *
+ *
Defaults to true
+ */
+ gridOptions.enableInfiniteScroll = gridOptions.enableInfiniteScroll !== false;
+
+ /**
+ * @ngdoc property
+ * @name infiniteScrollRowsFromEnd
+ * @propertyOf ui.grid.class:GridOptions
+ * @description This setting controls how close to the end of the dataset a user gets before
+ * more data is requested by the infinite scroll, whether scrolling up or down. This allows you to
+ * 'prefetch' rows before the user actually runs out of scrolling.
+ *
+ * Note that if you set this value too high it may give jumpy scrolling behaviour, if you're getting
+ * this behaviour you could use the `saveScrollPercentageMethod` right before loading your data, and we'll
+ * preserve that scroll position
+ *
+ *
Defaults to 20
+ */
+ gridOptions.infiniteScrollRowsFromEnd = gridOptions.infiniteScrollRowsFromEnd || 20;
+
+ /**
+ * @ngdoc property
+ * @name infiniteScrollUp
+ * @propertyOf ui.grid.class:GridOptions
+ * @description Whether you allow infinite scroll up, implying that the first page of data
+ * you have displayed is in the middle of your data set. If set to true then we trigger the
+ * needMoreDataTop event when the user hits the top of the scrollbar.
+ *
Defaults to false
+ */
+ gridOptions.infiniteScrollUp = gridOptions.infiniteScrollUp === true;
+
+ /**
+ * @ngdoc property
+ * @name infiniteScrollDown
+ * @propertyOf ui.grid.class:GridOptions
+ * @description Whether you allow infinite scroll down, implying that the first page of data
+ * you have displayed is in the middle of your data set. If set to true then we trigger the
+ * needMoreData event when the user hits the bottom of the scrollbar.
+ *
Defaults to true
+ */
+ gridOptions.infiniteScrollDown = gridOptions.infiniteScrollDown !== false;
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name setScrollDirections
+ * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService
+ * @description Sets the scrollUp and scrollDown flags, handling nulls and undefined,
+ * and also sets the grid.suppressParentScroll
+ * @param {grid} grid the grid we're operating on
+ * @param {boolean} scrollUp whether there are pages available up - defaults to false
+ * @param {boolean} scrollDown whether there are pages available down - defaults to true
+ */
+ setScrollDirections: function ( grid, scrollUp, scrollDown ) {
+ grid.infiniteScroll.scrollUp = ( scrollUp === true );
+ grid.suppressParentScrollUp = ( scrollUp === true );
+
+ grid.infiniteScroll.scrollDown = ( scrollDown !== false);
+ grid.suppressParentScrollDown = ( scrollDown !== false);
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name handleScroll
+ * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService
+ * @description Called whenever the grid scrolls, determines whether the scroll should
+ * trigger an infinite scroll request for more data
+ * @param {object} args the args from the event
+ */
+ handleScroll: function (args) {
+ // don't request data if already waiting for data, or if source is coming from ui.grid.adjustInfiniteScrollPosition() function
+ if ( args.grid.infiniteScroll && args.grid.infiniteScroll.dataLoading || args.source === 'ui.grid.adjustInfiniteScrollPosition' ){
+ return;
+ }
+
+ if (args.y) {
+
+ // If the user is scrolling very quickly all the way to the top/bottom, the scroll handler can get confused
+ // about the direction. First we check if they've gone all the way, and data always is loaded in this case.
+ if (args.y.percentage === 0) {
+ args.grid.scrollDirection = uiGridConstants.scrollDirection.UP;
+ service.loadData(args.grid);
+ } else if (args.y.percentage === 1) {
+ args.grid.scrollDirection = uiGridConstants.scrollDirection.DOWN;
+ service.loadData(args.grid);
+ } else { // Scroll position is somewhere in between top/bottom, so determine whether it's far enough to load more data.
+ var percentage;
+ var targetPercentage = args.grid.options.infiniteScrollRowsFromEnd / args.grid.renderContainers.body.visibleRowCache.length;
+ if (args.grid.scrollDirection === uiGridConstants.scrollDirection.UP ) {
+ percentage = args.y.percentage;
+ if (percentage <= targetPercentage){
+ service.loadData(args.grid);
+ }
+ } else if (args.grid.scrollDirection === uiGridConstants.scrollDirection.DOWN) {
+ percentage = 1 - args.y.percentage;
+ if (percentage <= targetPercentage){
+ service.loadData(args.grid);
+ }
+ }
+ }
+ }
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name loadData
+ * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService
+ * @description This function fires 'needLoadMoreData' or 'needLoadMoreDataTop' event based on scrollDirection
+ * and whether there are more pages upwards or downwards. It also stores the number of rows that we had previously,
+ * and clears out any saved scroll position so that we know whether or not the user calls `saveScrollPercentage`
+ * @param {Grid} grid the grid we're working on
+ */
+ loadData: function (grid) {
+ // save number of currently visible rows to calculate new scroll position later - we know that we want
+ // to be at approximately the row we're currently at
+ grid.infiniteScroll.previousVisibleRows = grid.renderContainers.body.visibleRowCache.length;
+ grid.infiniteScroll.direction = grid.scrollDirection;
+ delete grid.infiniteScroll.prevScrollTop;
+
+ if (grid.scrollDirection === uiGridConstants.scrollDirection.UP && grid.infiniteScroll.scrollUp ) {
+ grid.infiniteScroll.dataLoading = true;
+ grid.api.infiniteScroll.raise.needLoadMoreDataTop();
+ } else if (grid.scrollDirection === uiGridConstants.scrollDirection.DOWN && grid.infiniteScroll.scrollDown ) {
+ grid.infiniteScroll.dataLoading = true;
+ grid.api.infiniteScroll.raise.needLoadMoreData();
+ }
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name adjustScroll
+ * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService
+ * @description Once we are informed that data has been loaded, adjust the scroll position to account for that
+ * addition and to make things look clean.
+ *
+ * If we're scrolling up we scroll to the first row of the old data set -
+ * so we're assuming that you would have gotten to the top of the grid (from the 20% need more data trigger) by
+ * the time the data comes back. If we're scrolling down we scroll to the last row of the old data set - so we're
+ * assuming that you would have gotten to the bottom of the grid (from the 80% need more data trigger) by the time
+ * the data comes back.
+ *
+ * Neither of these are good assumptions, but making this a smoother experience really requires
+ * that trigger to not be a percentage, and to be much closer to the end of the data (say, 5 rows off the end). Even then
+ * it'd be better still to actually run into the end. But if the data takes a while to come back, they may have scrolled
+ * somewhere else in the mean-time, in which case they'll get a jump back to the new data. Anyway, this will do for
+ * now, until someone wants to do better.
+ * @param {Grid} grid the grid we're working on
+ * @returns {promise} a promise that is resolved when scrolling has finished
+ */
+ adjustScroll: function(grid){
+ var promise = $q.defer();
+ $rootScope.$applyAsync(function () {
+ var newPercentage, viewportHeight, rowHeight, newVisibleRows, oldTop, newTop;
+
+ viewportHeight = grid.getViewportHeight() + grid.headerHeight - grid.renderContainers.body.headerHeight - grid.scrollbarHeight;
+ rowHeight = grid.options.rowHeight;
+
+ if ( grid.infiniteScroll.direction === undefined ){
+ // called from initialize, tweak our scroll up a little
+ service.adjustInfiniteScrollPosition(grid, 0);
+ }
+
+ newVisibleRows = grid.getVisibleRowCount();
+
+ // in case not enough data is loaded to enable scroller - load more data
+ var canvasHeight = rowHeight * newVisibleRows;
+ if (grid.infiniteScroll.scrollDown && (viewportHeight > canvasHeight)) {
+ grid.api.infiniteScroll.raise.needLoadMoreData();
+ }
+
+ if ( grid.infiniteScroll.direction === uiGridConstants.scrollDirection.UP ){
+ oldTop = grid.infiniteScroll.prevScrollTop || 0;
+ newTop = oldTop + (newVisibleRows - grid.infiniteScroll.previousVisibleRows)*rowHeight;
+ service.adjustInfiniteScrollPosition(grid, newTop);
+ $rootScope.$applyAsync( function() {
+ promise.resolve();
+ });
+ }
+
+ if ( grid.infiniteScroll.direction === uiGridConstants.scrollDirection.DOWN ){
+ newTop = grid.infiniteScroll.prevScrollTop || (grid.infiniteScroll.previousVisibleRows*rowHeight - viewportHeight);
+ service.adjustInfiniteScrollPosition(grid, newTop);
+ $rootScope.$applyAsync( function() {
+ promise.resolve();
+ });
+ }
+ }, 0);
+
+ return promise.promise;
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name adjustInfiniteScrollPosition
+ * @methodOf ui.grid.infiniteScroll.service:uiGridInfiniteScrollService
+ * @description This function fires 'needLoadMoreData' or 'needLoadMoreDataTop' event based on scrollDirection
+ * @param {Grid} grid the grid we're working on
+ * @param {number} scrollTop the position through the grid that we want to scroll to
+ */
+ adjustInfiniteScrollPosition: function (grid, scrollTop) {
+ var scrollEvent = new ScrollEvent(grid, null, null, 'ui.grid.adjustInfiniteScrollPosition'),
+ visibleRows = grid.getVisibleRowCount(),
+ viewportHeight = grid.getViewportHeight() + grid.headerHeight - grid.renderContainers.body.headerHeight - grid.scrollbarHeight,
+ rowHeight = grid.options.rowHeight,
+ scrollHeight = visibleRows*rowHeight-viewportHeight;
+
+ //for infinite scroll, if there are pages upwards then never allow it to be at the zero position so the up button can be active
+ if (scrollTop === 0 && grid.infiniteScroll.scrollUp) {
+ // using pixels results in a relative scroll, hence we have to use percentage
+ scrollEvent.y = {percentage: 1/scrollHeight};
+ }
+ else {
+ scrollEvent.y = {percentage: scrollTop/scrollHeight};
+ }
+ grid.scrollContainers('', scrollEvent);
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name dataRemovedTop
+ * @methodOf ui.grid.infiniteScroll.api:PublicAPI
+ * @description Adjusts the scroll position after you've removed data at the top. You should
+ * have called `saveScrollPercentage` before you remove the data, and if you're doing this in
+ * response to a `needMoreData` you should wait until the promise from `loadData` has resolved
+ * before you start removing data
+ * @param {Grid} grid the grid we're working on
+ * @param {boolean} scrollUp flag that there are pages upwards, fire
+ * infinite scroll events upward
+ * @param {boolean} scrollDown flag that there are pages downwards, so
+ * fire infinite scroll events downward
+ */
+ dataRemovedTop: function( grid, scrollUp, scrollDown ) {
+ var newVisibleRows, oldTop, newTop, rowHeight;
+ service.setScrollDirections( grid, scrollUp, scrollDown );
+
+ newVisibleRows = grid.renderContainers.body.visibleRowCache.length;
+ oldTop = grid.infiniteScroll.prevScrollTop;
+ rowHeight = grid.options.rowHeight;
+
+ // since we removed from the top, our new scroll row will be the old scroll row less the number
+ // of rows removed
+ newTop = oldTop - ( grid.infiniteScroll.previousVisibleRows - newVisibleRows )*rowHeight;
+
+ service.adjustInfiniteScrollPosition( grid, newTop );
+ },
+
+ /**
+ * @ngdoc function
+ * @name dataRemovedBottom
+ * @methodOf ui.grid.infiniteScroll.api:PublicAPI
+ * @description Adjusts the scroll position after you've removed data at the bottom. You should
+ * have called `saveScrollPercentage` before you remove the data, and if you're doing this in
+ * response to a `needMoreData` you should wait until the promise from `loadData` has resolved
+ * before you start removing data
+ * @param {Grid} grid the grid we're working on
+ * @param {boolean} scrollUp flag that there are pages upwards, fire
+ * infinite scroll events upward
+ * @param {boolean} scrollDown flag that there are pages downwards, so
+ * fire infinite scroll events downward
+ */
+ dataRemovedBottom: function( grid, scrollUp, scrollDown ) {
+ var newTop;
+ service.setScrollDirections( grid, scrollUp, scrollDown );
+
+ newTop = grid.infiniteScroll.prevScrollTop;
+
+ service.adjustInfiniteScrollPosition( grid, newTop );
+ }
+ };
+ return service;
+ }]);
+ /**
+ * @ngdoc directive
+ * @name ui.grid.infiniteScroll.directive:uiGridInfiniteScroll
+ * @element div
+ * @restrict A
+ *
+ * @description Adds infinite scroll features to grid
+ *
+ * @example
+
+ * .ui-grid-column-menu-button {
+ * display: block;
+ * }
+ *
+ */
+ /**
+ * @ngdoc property
+ * @name enableColumnMenus
+ * @propertyOf ui.grid.class:GridOptions.columnDef
+ * @description Override for column menus everywhere - if set to false then you get no
+ * column menus. Defaults to true.
+ *
+ */
+
+ $scope.offAllEvents();
+
+ if ($scope.sortable || $scope.colMenu) {
+ $scope.onDownEvents();
+
+ $scope.$on('$destroy', function () {
+ $scope.offAllEvents();
+ });
+ }
+ };
+
+/*
+ $scope.$watch('col', function (n, o) {
+ if (n !== o) {
+ // See if the column's internal class has changed
+ var newColClass = $scope.col.getColClass(false);
+ if (newColClass !== initColClass) {
+ $elm.removeClass(initColClass);
+ $elm.addClass(newColClass);
+ initColClass = newColClass;
+ }
+ }
+ });
+*/
+ updateHeaderOptions();
+
+ // Register a data change watch that would get triggered whenever someone edits a cell or modifies column defs
+ var dataChangeDereg = $scope.grid.registerDataChangeCallback( updateHeaderOptions, [uiGridConstants.dataChange.COLUMN]);
+
+ $scope.$on( '$destroy', dataChangeDereg );
+
+ $scope.handleClick = function(event) {
+ // If the shift key is being held down, add this column to the sort
+ var add = false;
+ if (event.shiftKey) {
+ add = true;
+ }
+
+ // Sort this column then rebuild the grid's rows
+ uiGridCtrl.grid.sortColumn($scope.col, add)
+ .then(function () {
+ if (uiGridCtrl.columnMenuScope) { uiGridCtrl.columnMenuScope.hideMenu(); }
+ uiGridCtrl.grid.refresh();
+ }).catch(angular.noop);
+ };
+
+ $scope.headerCellArrowKeyDown = function(event) {
+ if (event.keyCode === 32 || event.keyCode === 13) {
+ event.preventDefault();
+ $scope.toggleMenu(event);
+ }
+ };
+
+ $scope.toggleMenu = function(event) {
+
+ event.stopPropagation();
+
+ // If the menu is already showing...
+ if (uiGridCtrl.columnMenuScope.menuShown) {
+ // ... and we're the column the menu is on...
+ if (uiGridCtrl.columnMenuScope.col === $scope.col) {
+ // ... hide it
+ uiGridCtrl.columnMenuScope.hideMenu();
+ }
+ // ... and we're NOT the column the menu is on
+ else {
+ // ... move the menu to our column
+ uiGridCtrl.columnMenuScope.showMenu($scope.col, $elm);
+ }
+ }
+ // If the menu is NOT showing
+ else {
+ // ... show it on our column
+ uiGridCtrl.columnMenuScope.showMenu($scope.col, $elm);
+ }
+ };
+ }
+ };
+ }
+ };
+
+ return uiGridHeaderCell;
+ }]);
+
+})();
+
+(function(){
+ 'use strict';
+
+ angular.module('ui.grid').directive('uiGridHeader', ['$templateCache', '$compile', 'uiGridConstants', 'gridUtil', '$timeout', 'ScrollEvent',
+ function($templateCache, $compile, uiGridConstants, gridUtil, $timeout, ScrollEvent) {
+ var defaultTemplate = 'ui-grid/ui-grid-header';
+ var emptyTemplate = 'ui-grid/ui-grid-no-header';
+
+ return {
+ restrict: 'EA',
+ // templateUrl: 'ui-grid/ui-grid-header',
+ replace: true,
+ // priority: 1000,
+ require: ['^uiGrid', '^uiGridRenderContainer'],
+ scope: true,
+ compile: function($elm, $attrs) {
+ return {
+ pre: function ($scope, $elm, $attrs, controllers) {
+ var uiGridCtrl = controllers[0];
+ var containerCtrl = controllers[1];
+
+ $scope.grid = uiGridCtrl.grid;
+ $scope.colContainer = containerCtrl.colContainer;
+
+ updateHeaderReferences();
+
+ var headerTemplate;
+ if (!$scope.grid.options.showHeader) {
+ headerTemplate = emptyTemplate;
+ }
+ else {
+ headerTemplate = ($scope.grid.options.headerTemplate) ? $scope.grid.options.headerTemplate : defaultTemplate;
+ }
+
+ gridUtil.getTemplate(headerTemplate)
+ .then(function (contents) {
+ var template = angular.element(contents);
+
+ var newElm = $compile(template)($scope);
+ $elm.replaceWith(newElm);
+
+ // And update $elm to be the new element
+ $elm = newElm;
+
+ updateHeaderReferences();
+
+ if (containerCtrl) {
+ // Inject a reference to the header viewport (if it exists) into the grid controller for use in the horizontal scroll handler below
+ var headerViewport = $elm[0].getElementsByClassName('ui-grid-header-viewport')[0];
+
+
+ if (headerViewport) {
+ containerCtrl.headerViewport = headerViewport;
+ angular.element(headerViewport).on('scroll', scrollHandler);
+ $scope.$on('$destroy', function () {
+ angular.element(headerViewport).off('scroll', scrollHandler);
+ });
+ }
+ }
+
+ $scope.grid.queueRefresh();
+ }).catch(angular.noop);
+
+ function updateHeaderReferences() {
+ containerCtrl.header = containerCtrl.colContainer.header = $elm;
+
+ var headerCanvases = $elm[0].getElementsByClassName('ui-grid-header-canvas');
+
+ if (headerCanvases.length > 0) {
+ containerCtrl.headerCanvas = containerCtrl.colContainer.headerCanvas = headerCanvases[0];
+ }
+ else {
+ containerCtrl.headerCanvas = null;
+ }
+ }
+
+ function scrollHandler(evt) {
+ if (uiGridCtrl.grid.isScrollingHorizontally) {
+ return;
+ }
+ var newScrollLeft = gridUtil.normalizeScrollLeft(containerCtrl.headerViewport, uiGridCtrl.grid);
+ var horizScrollPercentage = containerCtrl.colContainer.scrollHorizontal(newScrollLeft);
+
+ var scrollEvent = new ScrollEvent(uiGridCtrl.grid, null, containerCtrl.colContainer, ScrollEvent.Sources.ViewPortScroll);
+ scrollEvent.newScrollLeft = newScrollLeft;
+ if ( horizScrollPercentage > -1 ){
+ scrollEvent.x = { percentage: horizScrollPercentage };
+ }
+
+ uiGridCtrl.grid.scrollContainers(null, scrollEvent);
+ }
+ },
+
+ post: function ($scope, $elm, $attrs, controllers) {
+ var uiGridCtrl = controllers[0];
+ var containerCtrl = controllers[1];
+
+ // gridUtil.logDebug('ui-grid-header link');
+
+ var grid = uiGridCtrl.grid;
+
+ // Don't animate header cells
+ gridUtil.disableAnimations($elm);
+
+ function updateColumnWidths() {
+ // this styleBuilder always runs after the renderContainer, so we can rely on the column widths
+ // already being populated correctly
+
+ var columnCache = containerCtrl.colContainer.visibleColumnCache;
+
+ // Build the CSS
+ // uiGridCtrl.grid.columns.forEach(function (column) {
+ var ret = '';
+ var canvasWidth = 0;
+ columnCache.forEach(function (column) {
+ ret = ret + column.getColClassDefinition();
+ canvasWidth += column.drawnWidth;
+ });
+
+ containerCtrl.colContainer.canvasWidth = canvasWidth;
+
+ // Return the styles back to buildStyles which pops them into the `customStyles` scope variable
+ return ret;
+ }
+
+ containerCtrl.header = $elm;
+
+ var headerViewport = $elm[0].getElementsByClassName('ui-grid-header-viewport')[0];
+ if (headerViewport) {
+ containerCtrl.headerViewport = headerViewport;
+ }
+
+ //todo: remove this if by injecting gridCtrl into unit tests
+ if (uiGridCtrl) {
+ uiGridCtrl.grid.registerStyleComputation({
+ priority: 15,
+ func: updateColumnWidths
+ });
+ }
+ }
+ };
+ }
+ };
+ }]);
+
+})();
+
+(function(){
+
+angular.module('ui.grid')
+.service('uiGridGridMenuService', [ 'gridUtil', 'i18nService', 'uiGridConstants', function( gridUtil, i18nService, uiGridConstants ) {
+ /**
+ * @ngdoc service
+ * @name ui.grid.uiGridGridMenuService
+ *
+ * @description Methods for working with the grid menu
+ */
+
+ var service = {
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.uiGridGridMenuService
+ * @name initialize
+ * @description Sets up the gridMenu. Most importantly, sets our
+ * scope onto the grid object as grid.gridMenuScope, allowing us
+ * to operate when passed only the grid. Second most importantly,
+ * we register the 'addToGridMenu' and 'removeFromGridMenu' methods
+ * on the core api.
+ * @param {$scope} $scope the scope of this gridMenu
+ * @param {Grid} grid the grid to which this gridMenu is associated
+ */
+ initialize: function( $scope, grid ){
+ grid.gridMenuScope = $scope;
+ $scope.grid = grid;
+ $scope.registeredMenuItems = [];
+
+ // not certain this is needed, but would be bad to create a memory leak
+ $scope.$on('$destroy', function() {
+ if ( $scope.grid && $scope.grid.gridMenuScope ){
+ $scope.grid.gridMenuScope = null;
+ }
+ if ( $scope.grid ){
+ $scope.grid = null;
+ }
+ if ( $scope.registeredMenuItems ){
+ $scope.registeredMenuItems = null;
+ }
+ });
+
+ $scope.registeredMenuItems = [];
+
+ /**
+ * @ngdoc function
+ * @name addToGridMenu
+ * @methodOf ui.grid.core.api:PublicApi
+ * @description add items to the grid menu. Used by features
+ * to add their menu items if they are enabled, can also be used by
+ * end users to add menu items. This method has the advantage of allowing
+ * remove again, which can simplify management of which items are included
+ * in the menu when. (Noting that in most cases the shown and active functions
+ * provide a better way to handle visibility of menu items)
+ * @param {Grid} grid the grid on which we are acting
+ * @param {array} items menu items in the format as described in the tutorial, with
+ * the added note that if you want to use remove you must also specify an `id` field,
+ * which is provided when you want to remove an item. The id should be unique.
+ *
+ */
+ grid.api.registerMethod( 'core', 'addToGridMenu', service.addToGridMenu );
+
+ /**
+ * @ngdoc function
+ * @name removeFromGridMenu
+ * @methodOf ui.grid.core.api:PublicApi
+ * @description Remove an item from the grid menu based on a provided id. Assumes
+ * that the id is unique, removes only the last instance of that id. Does nothing if
+ * the specified id is not found
+ * @param {Grid} grid the grid on which we are acting
+ * @param {string} id the id we'd like to remove from the menu
+ *
+ */
+ grid.api.registerMethod( 'core', 'removeFromGridMenu', service.removeFromGridMenu );
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name addToGridMenu
+ * @propertyOf ui.grid.uiGridGridMenuService
+ * @description add items to the grid menu. Used by features
+ * to add their menu items if they are enabled, can also be used by
+ * end users to add menu items. This method has the advantage of allowing
+ * remove again, which can simplify management of which items are included
+ * in the menu when. (Noting that in most cases the shown and active functions
+ * provide a better way to handle visibility of menu items)
+ * @param {Grid} grid the grid on which we are acting
+ * @param {array} menuItems menu items in the format as described in the tutorial, with
+ * the added note that if you want to use remove you must also specify an `id` field,
+ * which is provided when you want to remove an item. The id should be unique.
+ *
+ */
+ addToGridMenu: function( grid, menuItems ) {
+ if ( !angular.isArray( menuItems ) ) {
+ gridUtil.logError( 'addToGridMenu: menuItems must be an array, and is not, not adding any items');
+ } else {
+ if ( grid.gridMenuScope ){
+ grid.gridMenuScope.registeredMenuItems = grid.gridMenuScope.registeredMenuItems ? grid.gridMenuScope.registeredMenuItems : [];
+ grid.gridMenuScope.registeredMenuItems = grid.gridMenuScope.registeredMenuItems.concat( menuItems );
+ } else {
+ gridUtil.logError( 'Asked to addToGridMenu, but gridMenuScope not present. Timing issue? Please log issue with ui-grid');
+ }
+ }
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name removeFromGridMenu
+ * @methodOf ui.grid.uiGridGridMenuService
+ * @description Remove an item from the grid menu based on a provided id. Assumes
+ * that the id is unique, removes only the last instance of that id. Does nothing if
+ * the specified id is not found. If there is no gridMenuScope or registeredMenuItems
+ * then do nothing silently - the desired result is those menu items not be present and they
+ * aren't.
+ * @param {Grid} grid the grid on which we are acting
+ * @param {string} id the id we'd like to remove from the menu
+ *
+ */
+ removeFromGridMenu: function( grid, id ){
+ var foundIndex = -1;
+
+ if ( grid && grid.gridMenuScope ){
+ grid.gridMenuScope.registeredMenuItems.forEach( function( value, index ) {
+ if ( value.id === id ){
+ if (foundIndex > -1) {
+ gridUtil.logError( 'removeFromGridMenu: found multiple items with the same id, removing only the last' );
+ } else {
+
+ foundIndex = index;
+ }
+ }
+ });
+ }
+
+ if ( foundIndex > -1 ){
+ grid.gridMenuScope.registeredMenuItems.splice( foundIndex, 1 );
+ }
+ },
+
+
+ /**
+ * @ngdoc array
+ * @name gridMenuCustomItems
+ * @propertyOf ui.grid.class:GridOptions
+ * @description (optional) An array of menu items that should be added to
+ * the gridMenu. Follow the format documented in the tutorial for column
+ * menu customisation. The context provided to the action function will
+ * include context.grid. An alternative if working with dynamic menus is to use the
+ * provided api - core.addToGridMenu and core.removeFromGridMenu, which handles
+ * some of the management of items for you.
+ *
+ */
+ /**
+ * @ngdoc boolean
+ * @name gridMenuShowHideColumns
+ * @propertyOf ui.grid.class:GridOptions
+ * @description true by default, whether the grid menu should allow hide/show
+ * of columns
+ *
+ */
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.uiGridGridMenuService
+ * @name getMenuItems
+ * @description Decides the menu items to show in the menu. This is a
+ * combination of:
+ *
+ * - the default menu items that are always included,
+ * - any menu items that have been provided through the addMenuItem api. These
+ * are typically added by features within the grid
+ * - any menu items included in grid.options.gridMenuCustomItems. These can be
+ * changed dynamically, as they're always recalculated whenever we show the
+ * menu
+ * @param {$scope} $scope the scope of this gridMenu, from which we can find all
+ * the information that we need
+ * @returns {Array} an array of menu items that can be shown
+ */
+ getMenuItems: function( $scope ) {
+ var menuItems = [
+ // this is where we add any menu items we want to always include
+ ];
+
+ if ( $scope.grid.options.gridMenuCustomItems ){
+ if ( !angular.isArray( $scope.grid.options.gridMenuCustomItems ) ){
+ gridUtil.logError( 'gridOptions.gridMenuCustomItems must be an array, and is not');
+ } else {
+ menuItems = menuItems.concat( $scope.grid.options.gridMenuCustomItems );
+ }
+ }
+
+ var clearFilters = [{
+ title: i18nService.getSafeText('gridMenu.clearAllFilters'),
+ action: function ($event) {
+ $scope.grid.clearAllFilters();
+ },
+ shown: function() {
+ return $scope.grid.options.enableFiltering;
+ },
+ order: 100
+ }];
+ menuItems = menuItems.concat( clearFilters );
+
+ menuItems = menuItems.concat( $scope.registeredMenuItems );
+
+ if ( $scope.grid.options.gridMenuShowHideColumns !== false ){
+ menuItems = menuItems.concat( service.showHideColumns( $scope ) );
+ }
+
+ menuItems.sort(function(a, b){
+ return a.order - b.order;
+ });
+
+ return menuItems;
+ },
+
+
+ /**
+ * @ngdoc array
+ * @name gridMenuTitleFilter
+ * @propertyOf ui.grid.class:GridOptions
+ * @description (optional) A function that takes a title string
+ * (usually the col.displayName), and converts it into a display value. The function
+ * must return either a string or a promise.
+ *
+ * Used for internationalization of the grid menu column names - for angular-translate
+ * you can pass $translate as the function, for i18nService you can pass getSafeText as the
+ * function
+ * @example
+ *
+ * gridOptions = {
+ * gridMenuTitleFilter: $translate
+ * }
+ *
+ */
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.uiGridGridMenuService
+ * @name showHideColumns
+ * @description Adds two menu items for each of the columns in columnDefs. One
+ * menu item for hide, one menu item for show. Each is visible when appropriate
+ * (show when column is not visible, hide when column is visible). Each toggles
+ * the visible property on the columnDef using toggleColumnVisibility
+ * @param {$scope} $scope of a gridMenu, which contains a reference to the grid
+ */
+ showHideColumns: function( $scope ){
+ var showHideColumns = [];
+ if ( !$scope.grid.options.columnDefs || $scope.grid.options.columnDefs.length === 0 || $scope.grid.columns.length === 0 ) {
+ return showHideColumns;
+ }
+
+ function isColumnVisible(colDef) {
+ return colDef.visible === true || colDef.visible === undefined;
+ }
+
+ // add header for columns
+ showHideColumns.push({
+ title: i18nService.getSafeText('gridMenu.columns'),
+ order: 300,
+ templateUrl: 'ui-grid/ui-grid-menu-header-item'
+ });
+
+ $scope.grid.options.gridMenuTitleFilter = $scope.grid.options.gridMenuTitleFilter ? $scope.grid.options.gridMenuTitleFilter : function( title ) { return title; };
+
+ $scope.grid.options.columnDefs.forEach( function( colDef, index ){
+ if ( colDef.enableHiding !== false ){
+ // add hide menu item - shows an OK icon as we only show when column is already visible
+ var menuItem = {
+ icon: isColumnVisible(colDef) ? 'ui-grid-icon-ok' : 'ui-grid-icon-cancel',
+ action: function($event) {
+ $event.stopPropagation();
+
+ service.toggleColumnVisibility( this.context.gridCol );
+
+ if ($event.target && $event.target.firstChild) {
+ $event.target.firstChild.className = isColumnVisible(this.context.gridCol.colDef) ?
+ 'ui-grid-icon-ok' : 'ui-grid-icon-cancel';
+ }
+ },
+ shown: function() {
+ return this.context.gridCol.colDef.enableHiding !== false;
+ },
+ context: { gridCol: $scope.grid.getColumn(colDef.name || colDef.field) },
+ leaveOpen: true,
+ order: 301 + index
+ };
+ service.setMenuItemTitle( menuItem, colDef, $scope.grid );
+ showHideColumns.push( menuItem );
+ }
+ });
+ return showHideColumns;
+ },
+
+
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.uiGridGridMenuService
+ * @name setMenuItemTitle
+ * @description Handles the response from gridMenuTitleFilter, adding it directly to the menu
+ * item if it returns a string, otherwise waiting for the promise to resolve or reject then
+ * putting the result into the title
+ * @param {object} menuItem the menuItem we want to put the title on
+ * @param {object} colDef the colDef from which we can get displayName, name or field
+ * @param {Grid} grid the grid, from which we can get the options.gridMenuTitleFilter
+ *
+ */
+ setMenuItemTitle: function( menuItem, colDef, grid ){
+ var title = grid.options.gridMenuTitleFilter( colDef.displayName || gridUtil.readableColumnName(colDef.name) || colDef.field );
+
+ if ( typeof(title) === 'string' ){
+ menuItem.title = title;
+ } else if ( title.then ){
+ // must be a promise
+ menuItem.title = "";
+ title.then( function( successValue ) {
+ menuItem.title = successValue;
+ }, function( errorValue ) {
+ menuItem.title = errorValue;
+ }).catch(angular.noop);
+ } else {
+ gridUtil.logError('Expected gridMenuTitleFilter to return a string or a promise, it has returned neither, bad config');
+ menuItem.title = 'badconfig';
+ }
+ },
+
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.uiGridGridMenuService
+ * @name toggleColumnVisibility
+ * @description Toggles the visibility of an individual column. Expects to be
+ * provided a context that has on it a gridColumn, which is the column that
+ * we'll operate upon. We change the visibility, and refresh the grid as appropriate
+ * @param {GridColumn} gridCol the column that we want to toggle
+ *
+ */
+ toggleColumnVisibility: function( gridCol ) {
+ gridCol.colDef.visible = !( gridCol.colDef.visible === true || gridCol.colDef.visible === undefined );
+
+ gridCol.grid.refresh();
+ gridCol.grid.api.core.notifyDataChange( uiGridConstants.dataChange.COLUMN );
+ gridCol.grid.api.core.raise.columnVisibilityChanged( gridCol );
+ }
+ };
+
+ return service;
+}])
+
+
+
+.directive('uiGridMenuButton', ['gridUtil', 'uiGridConstants', 'uiGridGridMenuService', 'i18nService',
+function (gridUtil, uiGridConstants, uiGridGridMenuService, i18nService) {
+
+ return {
+ priority: 0,
+ scope: true,
+ require: ['^uiGrid'],
+ templateUrl: 'ui-grid/ui-grid-menu-button',
+ replace: true,
+
+ link: function ($scope, $elm, $attrs, controllers) {
+ var uiGridCtrl = controllers[0];
+
+ // For the aria label
+ $scope.i18n = {
+ aria: i18nService.getSafeText('gridMenu.aria')
+ };
+
+ uiGridGridMenuService.initialize($scope, uiGridCtrl.grid);
+
+ $scope.shown = false;
+
+ $scope.toggleMenu = function () {
+ if ( $scope.shown ){
+ $scope.$broadcast('hide-menu');
+ $scope.shown = false;
+ } else {
+ $scope.menuItems = uiGridGridMenuService.getMenuItems( $scope );
+ $scope.$broadcast('show-menu');
+ $scope.shown = true;
+ }
+ };
+
+ $scope.$on('menu-hidden', function() {
+ $scope.shown = false;
+ gridUtil.focus.bySelector($elm, '.ui-grid-icon-container');
+ });
+ }
+ };
+
+}]);
+
+})();
+
+(function(){
+
+/**
+ * @ngdoc directive
+ * @name ui.grid.directive:uiGridMenu
+ * @element style
+ * @restrict A
+ *
+ * @description
+ * Allows us to interpolate expressions in `
+ I am in a box.
+
+
+ Example
+ *
+ * $scope.gridOptions = {
+ * customScroller: function myScrolling(uiGridViewport, scrollHandler) {
+ * uiGridViewport.on('scroll', function myScrollingOverride(event) {
+ * // Do something here
+ *
+ * scrollHandler(event);
+ * });
+ * }
+ * };
+ *
+ * @param {object} uiGridViewport Element being scrolled. (this gets passed in by the grid).
+ * @param {function} scrollHandler Function that needs to be called when scrolling happens. (this gets passed in by the grid).
+ */
+ if (grid && grid.options && grid.options.customScroller) {
+ grid.options.customScroller($elm, scrollHandler);
+ } else {
+ $elm.on('scroll', scrollHandler);
+ }
+
+ var ignoreScroll = false;
+
+ function scrollHandler(evt) {
+ //Leaving in this commented code in case it can someday be used
+ //It does improve performance, but because the horizontal scroll is normalized,
+ // using this code will lead to the column header getting slightly out of line with columns
+ //
+ //if (ignoreScroll && (grid.isScrollingHorizontally || grid.isScrollingHorizontally)) {
+ // //don't ask for scrollTop if we just set it
+ // ignoreScroll = false;
+ // return;
+ //}
+ //ignoreScroll = true;
+
+ var newScrollTop = $elm[0].scrollTop;
+ var newScrollLeft = gridUtil.normalizeScrollLeft($elm, grid);
+
+ var vertScrollPercentage = rowContainer.scrollVertical(newScrollTop);
+ var horizScrollPercentage = colContainer.scrollHorizontal(newScrollLeft);
+
+ var scrollEvent = new ScrollEvent(grid, rowContainer, colContainer, ScrollEvent.Sources.ViewPortScroll);
+ scrollEvent.newScrollLeft = newScrollLeft;
+ scrollEvent.newScrollTop = newScrollTop;
+ if ( horizScrollPercentage > -1 ){
+ scrollEvent.x = { percentage: horizScrollPercentage };
+ }
+
+ if ( vertScrollPercentage > -1 ){
+ scrollEvent.y = { percentage: vertScrollPercentage };
+ }
+
+ grid.scrollContainers($scope.$parent.containerId, scrollEvent);
+ }
+
+ if ($scope.$parent.bindScrollVertical) {
+ grid.addVerticalScrollSync($scope.$parent.containerId, syncVerticalScroll);
+ }
+
+ if ($scope.$parent.bindScrollHorizontal) {
+ grid.addHorizontalScrollSync($scope.$parent.containerId, syncHorizontalScroll);
+ grid.addHorizontalScrollSync($scope.$parent.containerId + 'header', syncHorizontalHeader);
+ grid.addHorizontalScrollSync($scope.$parent.containerId + 'footer', syncHorizontalFooter);
+ }
+
+ function syncVerticalScroll(scrollEvent){
+ containerCtrl.prevScrollArgs = scrollEvent;
+ var newScrollTop = scrollEvent.getNewScrollTop(rowContainer,containerCtrl.viewport);
+ $elm[0].scrollTop = newScrollTop;
+
+ }
+
+ function syncHorizontalScroll(scrollEvent){
+ containerCtrl.prevScrollArgs = scrollEvent;
+ var newScrollLeft = scrollEvent.getNewScrollLeft(colContainer, containerCtrl.viewport);
+ $elm[0].scrollLeft = gridUtil.denormalizeScrollLeft(containerCtrl.viewport,newScrollLeft, grid);
+ }
+
+ function syncHorizontalHeader(scrollEvent){
+ var newScrollLeft = scrollEvent.getNewScrollLeft(colContainer, containerCtrl.viewport);
+ if (containerCtrl.headerViewport) {
+ containerCtrl.headerViewport.scrollLeft = gridUtil.denormalizeScrollLeft(containerCtrl.viewport,newScrollLeft, grid);
+ }
+ }
+
+ function syncHorizontalFooter(scrollEvent){
+ var newScrollLeft = scrollEvent.getNewScrollLeft(colContainer, containerCtrl.viewport);
+ if (containerCtrl.footerViewport) {
+ containerCtrl.footerViewport.scrollLeft = gridUtil.denormalizeScrollLeft(containerCtrl.viewport,newScrollLeft, grid);
+ }
+ }
+
+ $scope.$on('$destroy', function unbindEvents() {
+ $elm.off();
+ });
+ },
+ controller: ['$scope', function ($scope) {
+ this.rowStyle = function (index) {
+ var rowContainer = $scope.rowContainer;
+ var colContainer = $scope.colContainer;
+
+ var styles = {};
+
+ if (rowContainer.currentTopRow !== 0){
+ //top offset based on hidden rows count
+ var translateY = "translateY("+ (rowContainer.currentTopRow * rowContainer.grid.options.rowHeight) +"px)";
+ styles['transform'] = translateY;
+ styles['-webkit-transform'] = translateY;
+ styles['-ms-transform'] = translateY;
+ }
+
+ if (colContainer.currentFirstColumn !== 0) {
+ if (colContainer.grid.isRTL()) {
+ styles['margin-right'] = colContainer.columnOffset + 'px';
+ }
+ else {
+ styles['margin-left'] = colContainer.columnOffset + 'px';
+ }
+ }
+
+ return styles;
+ };
+ }]
+ };
+ }
+ ]);
+
+})();
+
+(function() {
+
+angular.module('ui.grid')
+.directive('uiGridVisible', function uiGridVisibleAction() {
+ return function ($scope, $elm, $attr) {
+ $scope.$watch($attr.uiGridVisible, function (visible) {
+ // $elm.css('visibility', visible ? 'visible' : 'hidden');
+ $elm[visible ? 'removeClass' : 'addClass']('ui-grid-invisible');
+ });
+ };
+});
+
+})();
+(function () {
+ 'use strict';
+
+ angular.module('ui.grid').controller('uiGridController', ['$scope', '$element', '$attrs', 'gridUtil', '$q', 'uiGridConstants',
+ 'gridClassFactory', '$parse', '$compile',
+ function ($scope, $elm, $attrs, gridUtil, $q, uiGridConstants,
+ gridClassFactory, $parse, $compile) {
+ // gridUtil.logDebug('ui-grid controller');
+ var self = this;
+ var deregFunctions = [];
+
+ self.grid = gridClassFactory.createGrid($scope.uiGrid);
+
+ //assign $scope.$parent if appScope not already assigned
+ self.grid.appScope = self.grid.appScope || $scope.$parent;
+
+ $elm.addClass('grid' + self.grid.id);
+ self.grid.rtl = gridUtil.getStyles($elm[0])['direction'] === 'rtl';
+
+
+ // angular.extend(self.grid.options, );
+
+ //all properties of grid are available on scope
+ $scope.grid = self.grid;
+
+ if ($attrs.uiGridColumns) {
+ deregFunctions.push( $attrs.$observe('uiGridColumns', function(value) {
+ self.grid.options.columnDefs = angular.isString(value) ? angular.fromJson(value) : value;
+ self.grid.buildColumns()
+ .then(function(){
+ self.grid.preCompileCellTemplates();
+
+ self.grid.refreshCanvas(true);
+ }).catch(angular.noop);
+ }) );
+ }
+
+ // prevents an error from being thrown when the array is not defined yet and fastWatch is on
+ function getSize(array) {
+ return array ? array.length : 0;
+ }
+
+ // if fastWatch is set we watch only the length and the reference, not every individual object
+ if (self.grid.options.fastWatch) {
+ self.uiGrid = $scope.uiGrid;
+ if (angular.isString($scope.uiGrid.data)) {
+ deregFunctions.push( $scope.$parent.$watch($scope.uiGrid.data, dataWatchFunction) );
+ deregFunctions.push( $scope.$parent.$watch(function() {
+ if ( self.grid.appScope[$scope.uiGrid.data] ){
+ return self.grid.appScope[$scope.uiGrid.data].length;
+ } else {
+ return undefined;
+ }
+ }, dataWatchFunction) );
+ } else {
+ deregFunctions.push( $scope.$parent.$watch(function() { return $scope.uiGrid.data; }, dataWatchFunction) );
+ deregFunctions.push( $scope.$parent.$watch(function() { return getSize($scope.uiGrid.data); }, function(){ dataWatchFunction($scope.uiGrid.data); }) );
+ }
+ deregFunctions.push( $scope.$parent.$watch(function() { return $scope.uiGrid.columnDefs; }, columnDefsWatchFunction) );
+ deregFunctions.push( $scope.$parent.$watch(function() { return getSize($scope.uiGrid.columnDefs); }, function(){ columnDefsWatchFunction($scope.uiGrid.columnDefs); }) );
+ } else {
+ if (angular.isString($scope.uiGrid.data)) {
+ deregFunctions.push( $scope.$parent.$watchCollection($scope.uiGrid.data, dataWatchFunction) );
+ } else {
+ deregFunctions.push( $scope.$parent.$watchCollection(function() { return $scope.uiGrid.data; }, dataWatchFunction) );
+ }
+ deregFunctions.push( $scope.$parent.$watchCollection(function() { return $scope.uiGrid.columnDefs; }, columnDefsWatchFunction) );
+ }
+
+
+ function columnDefsWatchFunction(n, o) {
+ if (n && n !== o) {
+ self.grid.options.columnDefs = $scope.uiGrid.columnDefs;
+ self.grid.callDataChangeCallbacks(uiGridConstants.dataChange.COLUMN, {
+ orderByColumnDefs: true,
+ preCompileCellTemplates: true
+ });
+ }
+ }
+
+ var mostRecentData;
+
+ function dataWatchFunction(newData) {
+ // gridUtil.logDebug('dataWatch fired');
+ var promises = [];
+
+ if ( self.grid.options.fastWatch ) {
+ if (angular.isString($scope.uiGrid.data)) {
+ newData = self.grid.appScope.$eval($scope.uiGrid.data);
+ } else {
+ newData = $scope.uiGrid.data;
+ }
+ }
+
+ mostRecentData = newData;
+
+ if (newData) {
+ // columns length is greater than the number of row header columns, which don't count because they're created automatically
+ var hasColumns = self.grid.columns.length > (self.grid.rowHeaderColumns ? self.grid.rowHeaderColumns.length : 0);
+
+ if (
+ // If we have no columns
+ !hasColumns &&
+ // ... and we don't have a ui-grid-columns attribute, which would define columns for us
+ !$attrs.uiGridColumns &&
+ // ... and we have no pre-defined columns
+ self.grid.options.columnDefs.length === 0 &&
+ // ... but we DO have data
+ newData.length > 0
+ ) {
+ // ... then build the column definitions from the data that we have
+ self.grid.buildColumnDefsFromData(newData);
+ }
+
+ // If we haven't built columns before and either have some columns defined or some data defined
+ if (!hasColumns && (self.grid.options.columnDefs.length > 0 || newData.length > 0)) {
+ // Build the column set, then pre-compile the column cell templates
+ promises.push(self.grid.buildColumns()
+ .then(function() {
+ self.grid.preCompileCellTemplates();
+ }).catch(angular.noop));
+ }
+
+ $q.all(promises).then(function() {
+ // use most recent data, rather than the potentially outdated data passed into watcher handler
+ self.grid.modifyRows(mostRecentData)
+ .then(function () {
+ // if (self.viewport) {
+ self.grid.redrawInPlace(true);
+ // }
+
+ $scope.$evalAsync(function() {
+ self.grid.refreshCanvas(true);
+ self.grid.callDataChangeCallbacks(uiGridConstants.dataChange.ROW);
+ });
+ }).catch(angular.noop);
+ }).catch(angular.noop);
+ }
+ }
+
+ var styleWatchDereg = $scope.$watch(function () { return self.grid.styleComputations; }, function() {
+ self.grid.refreshCanvas(true);
+ });
+
+ $scope.$on('$destroy', function() {
+ deregFunctions.forEach( function( deregFn ){ deregFn(); });
+ styleWatchDereg();
+ });
+
+ self.fireEvent = function(eventName, args) {
+ args = args || {};
+
+ // Add the grid to the event arguments if it's not there
+ if (angular.isUndefined(args.grid)) {
+ args.grid = self.grid;
+ }
+
+ $scope.$broadcast(eventName, args);
+ };
+
+ self.innerCompile = function innerCompile(elm) {
+ $compile(elm)($scope);
+ };
+ }]);
+
+/**
+ * @ngdoc directive
+ * @name ui.grid.directive:uiGrid
+ * @element div
+ * @restrict EA
+ * @param {Object} uiGrid Options for the grid to use
+ *
+ * @description Create a very basic grid.
+ *
+ * @example
+
+ * use gridOptions.appScopeProvider to override the default assignment of $scope.$parent with any reference
+ */
+ self.appScope = self.options.appScopeProvider;
+
+ self.headerHeight = self.options.headerRowHeight;
+
+
+ /**
+ * @ngdoc object
+ * @name footerHeight
+ * @propertyOf ui.grid.class:Grid
+ * @description returns the total footer height gridFooter + columnFooter
+ */
+ self.footerHeight = self.calcFooterHeight();
+
+
+ /**
+ * @ngdoc object
+ * @name columnFooterHeight
+ * @propertyOf ui.grid.class:Grid
+ * @description returns the total column footer height
+ */
+ self.columnFooterHeight = self.calcColumnFooterHeight();
+
+ self.rtl = false;
+ self.gridHeight = 0;
+ self.gridWidth = 0;
+ self.columnBuilders = [];
+ self.rowBuilders = [];
+ self.rowsProcessors = [];
+ self.columnsProcessors = [];
+ self.styleComputations = [];
+ self.viewportAdjusters = [];
+ self.rowHeaderColumns = [];
+ self.dataChangeCallbacks = {};
+ self.verticalScrollSyncCallBackFns = {};
+ self.horizontalScrollSyncCallBackFns = {};
+
+ // self.visibleRowCache = [];
+
+ // Set of 'render' containers for self grid, which can render sets of rows
+ self.renderContainers = {};
+
+ // Create a
+ self.renderContainers.body = new GridRenderContainer('body', self);
+
+ self.cellValueGetterCache = {};
+
+ // Cached function to use with custom row templates
+ self.getRowTemplateFn = null;
+
+
+ //representation of the rows on the grid.
+ //these are wrapped references to the actual data rows (options.data)
+ self.rows = [];
+
+ //represents the columns on the grid
+ self.columns = [];
+
+ /**
+ * @ngdoc boolean
+ * @name isScrollingVertically
+ * @propertyOf ui.grid.class:Grid
+ * @description set to true when Grid is scrolling vertically. Set to false via debounced method
+ */
+ self.isScrollingVertically = false;
+
+ /**
+ * @ngdoc boolean
+ * @name isScrollingHorizontally
+ * @propertyOf ui.grid.class:Grid
+ * @description set to true when Grid is scrolling horizontally. Set to false via debounced method
+ */
+ self.isScrollingHorizontally = false;
+
+ /**
+ * @ngdoc property
+ * @name scrollDirection
+ * @propertyOf ui.grid.class:Grid
+ * @description set one of the {@link ui.grid.service:uiGridConstants#properties_scrollDirection uiGridConstants.scrollDirection}
+ * values (UP, DOWN, LEFT, RIGHT, NONE), which tells us which direction we are scrolling.
+ * Set to NONE via debounced method
+ */
+ self.scrollDirection = uiGridConstants.scrollDirection.NONE;
+
+ //if true, grid will not respond to any scroll events
+ self.disableScrolling = false;
+
+
+ function vertical (scrollEvent) {
+ self.isScrollingVertically = false;
+ self.api.core.raise.scrollEnd(scrollEvent);
+ self.scrollDirection = uiGridConstants.scrollDirection.NONE;
+ }
+
+ var debouncedVertical = gridUtil.debounce(vertical, self.options.scrollDebounce);
+ var debouncedVerticalMinDelay = gridUtil.debounce(vertical, 0);
+
+ function horizontal (scrollEvent) {
+ self.isScrollingHorizontally = false;
+ self.api.core.raise.scrollEnd(scrollEvent);
+ self.scrollDirection = uiGridConstants.scrollDirection.NONE;
+ }
+
+ var debouncedHorizontal = gridUtil.debounce(horizontal, self.options.scrollDebounce);
+ var debouncedHorizontalMinDelay = gridUtil.debounce(horizontal, 0);
+
+
+ /**
+ * @ngdoc function
+ * @name flagScrollingVertically
+ * @methodOf ui.grid.class:Grid
+ * @description sets isScrollingVertically to true and sets it to false in a debounced function
+ */
+ self.flagScrollingVertically = function(scrollEvent) {
+ if (!self.isScrollingVertically && !self.isScrollingHorizontally) {
+ self.api.core.raise.scrollBegin(scrollEvent);
+ }
+ self.isScrollingVertically = true;
+ if (self.options.scrollDebounce === 0 || !scrollEvent.withDelay) {
+ debouncedVerticalMinDelay(scrollEvent);
+ }
+ else {
+ debouncedVertical(scrollEvent);
+ }
+ };
+
+ /**
+ * @ngdoc function
+ * @name flagScrollingHorizontally
+ * @methodOf ui.grid.class:Grid
+ * @description sets isScrollingHorizontally to true and sets it to false in a debounced function
+ */
+ self.flagScrollingHorizontally = function(scrollEvent) {
+ if (!self.isScrollingVertically && !self.isScrollingHorizontally) {
+ self.api.core.raise.scrollBegin(scrollEvent);
+ }
+ self.isScrollingHorizontally = true;
+ if (self.options.scrollDebounce === 0 || !scrollEvent.withDelay) {
+ debouncedHorizontalMinDelay(scrollEvent);
+ }
+ else {
+ debouncedHorizontal(scrollEvent);
+ }
+ };
+
+ self.scrollbarHeight = 0;
+ self.scrollbarWidth = 0;
+ if (self.options.enableHorizontalScrollbar !== uiGridConstants.scrollbars.NEVER) {
+ self.scrollbarHeight = gridUtil.getScrollbarWidth();
+ }
+
+ if (self.options.enableVerticalScrollbar !== uiGridConstants.scrollbars.NEVER) {
+ self.scrollbarWidth = gridUtil.getScrollbarWidth();
+ }
+
+
+
+ self.api = new GridApi(self);
+
+ /**
+ * @ngdoc function
+ * @name refresh
+ * @methodOf ui.grid.core.api:PublicApi
+ * @description Refresh the rendered grid on screen.
+ * The refresh method re-runs both the columnProcessors and the
+ * rowProcessors, as well as calling refreshCanvas to update all
+ * the grid sizing. In general you should prefer to use queueGridRefresh
+ * instead, which is basically a debounced version of refresh.
+ *
+ * If you only want to resize the grid, not regenerate all the rows
+ * and columns, you should consider directly calling refreshCanvas instead.
+ *
+ * @param {boolean} [rowsAltered] Optional flag for refreshing when the number of rows has changed
+ */
+ self.api.registerMethod( 'core', 'refresh', this.refresh );
+
+ /**
+ * @ngdoc function
+ * @name queueGridRefresh
+ * @methodOf ui.grid.core.api:PublicApi
+ * @description Request a refresh of the rendered grid on screen, if multiple
+ * calls to queueGridRefresh are made within a digest cycle only one will execute.
+ * The refresh method re-runs both the columnProcessors and the
+ * rowProcessors, as well as calling refreshCanvas to update all
+ * the grid sizing. In general you should prefer to use queueGridRefresh
+ * instead, which is basically a debounced version of refresh.
+ *
+ */
+ self.api.registerMethod( 'core', 'queueGridRefresh', this.queueGridRefresh );
+
+ /**
+ * @ngdoc function
+ * @name refreshRows
+ * @methodOf ui.grid.core.api:PublicApi
+ * @description Runs only the rowProcessors, columns remain as they were.
+ * It then calls redrawInPlace and refreshCanvas, which adjust the grid sizing.
+ * @returns {promise} promise that is resolved when render completes?
+ *
+ */
+ self.api.registerMethod( 'core', 'refreshRows', this.refreshRows );
+
+ /**
+ * @ngdoc function
+ * @name queueRefresh
+ * @methodOf ui.grid.core.api:PublicApi
+ * @description Requests execution of refreshCanvas, if multiple requests are made
+ * during a digest cycle only one will run. RefreshCanvas updates the grid sizing.
+ * @returns {promise} promise that is resolved when render completes?
+ *
+ */
+ self.api.registerMethod( 'core', 'queueRefresh', this.queueRefresh );
+
+ /**
+ * @ngdoc function
+ * @name handleWindowResize
+ * @methodOf ui.grid.core.api:PublicApi
+ * @description Trigger a grid resize, normally this would be picked
+ * up by a watch on window size, but in some circumstances it is necessary
+ * to call this manually
+ * @returns {promise} promise that is resolved when render completes?
+ *
+ */
+ self.api.registerMethod( 'core', 'handleWindowResize', this.handleWindowResize );
+
+
+ /**
+ * @ngdoc function
+ * @name addRowHeaderColumn
+ * @methodOf ui.grid.core.api:PublicApi
+ * @description adds a row header column to the grid
+ * @param {object} column def
+ * @param {number} order Determines order of header column on grid. Lower order means header
+ * is positioned to the left of higher order headers
+ *
+ */
+ self.api.registerMethod( 'core', 'addRowHeaderColumn', this.addRowHeaderColumn );
+
+ /**
+ * @ngdoc function
+ * @name scrollToIfNecessary
+ * @methodOf ui.grid.core.api:PublicApi
+ * @description Scrolls the grid to make a certain row and column combo visible,
+ * in the case that it is not completely visible on the screen already.
+ * @param {GridRow} gridRow row to make visible
+ * @param {GridColumn} gridCol column to make visible
+ * @returns {promise} a promise that is resolved when scrolling is complete
+ *
+ */
+ self.api.registerMethod( 'core', 'scrollToIfNecessary', function(gridRow, gridCol) { return self.scrollToIfNecessary(gridRow, gridCol);} );
+
+ /**
+ * @ngdoc function
+ * @name scrollTo
+ * @methodOf ui.grid.core.api:PublicApi
+ * @description Scroll the grid such that the specified
+ * row and column is in view
+ * @param {object} rowEntity gridOptions.data[] array instance to make visible
+ * @param {object} colDef to make visible
+ * @returns {promise} a promise that is resolved after any scrolling is finished
+ */
+ self.api.registerMethod( 'core', 'scrollTo', function (rowEntity, colDef) { return self.scrollTo(rowEntity, colDef);} );
+
+ /**
+ * @ngdoc function
+ * @name registerRowsProcessor
+ * @methodOf ui.grid.core.api:PublicApi
+ * @description
+ * Register a "rows processor" function. When the rows are updated,
+ * the grid calls each registered "rows processor", which has a chance
+ * to alter the set of rows (sorting, etc) as long as the count is not
+ * modified.
+ *
+ * @param {function(renderedRowsToProcess, columns )} processorFunction rows processor function, which
+ * is run in the context of the grid (i.e. this for the function will be the grid), and must
+ * return the updated rows list, which is passed to the next processor in the chain
+ * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room
+ * for other people to inject rows processors at intermediate priorities. Lower priority rowsProcessors run earlier.
+ *
+ * At present allRowsVisible is running at 50, sort manipulations running at 60-65, filter is running at 100,
+ * sort is at 200, grouping and treeview at 400-410, selectable rows at 500, pagination at 900 (pagination will generally want to be last)
+ */
+ self.api.registerMethod( 'core', 'registerRowsProcessor', this.registerRowsProcessor );
+
+ /**
+ * @ngdoc function
+ * @name registerColumnsProcessor
+ * @methodOf ui.grid.core.api:PublicApi
+ * @description
+ * Register a "columns processor" function. When the columns are updated,
+ * the grid calls each registered "columns processor", which has a chance
+ * to alter the set of columns as long as the count is not
+ * modified.
+ *
+ * @param {function(renderedColumnsToProcess, rows )} processorFunction columns processor function, which
+ * is run in the context of the grid (i.e. this for the function will be the grid), and must
+ * return the updated columns list, which is passed to the next processor in the chain
+ * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room
+ * for other people to inject columns processors at intermediate priorities. Lower priority columnsProcessors run earlier.
+ *
+ * At present allRowsVisible is running at 50, filter is running at 100, sort is at 200, grouping at 400, selectable rows at 500, pagination at 900 (pagination will generally want to be last)
+ */
+ self.api.registerMethod( 'core', 'registerColumnsProcessor', this.registerColumnsProcessor );
+
+
+
+ /**
+ * @ngdoc function
+ * @name sortHandleNulls
+ * @methodOf ui.grid.core.api:PublicApi
+ * @description A null handling method that can be used when building custom sort
+ * functions
+ * @example
+ *
+ * mySortFn = function(a, b) {
+ * var nulls = $scope.gridApi.core.sortHandleNulls(a, b);
+ * if ( nulls !== null ){
+ * return nulls;
+ * } else {
+ * // your code for sorting here
+ * };
+ *
+ * @param {object} a sort value a
+ * @param {object} b sort value b
+ * @returns {number} null if there were no nulls/undefineds, otherwise returns
+ * a sort value that should be passed back from the sort function
+ *
+ */
+ self.api.registerMethod( 'core', 'sortHandleNulls', rowSorter.handleNulls );
+
+
+ /**
+ * @ngdoc function
+ * @name sortChanged
+ * @methodOf ui.grid.core.api:PublicApi
+ * @description The sort criteria on one or more columns has
+ * changed. Provides as parameters the grid and the output of
+ * getColumnSorting, which is an array of gridColumns
+ * that have sorting on them, sorted in priority order.
+ *
+ * @param {$scope} scope The scope of the controller. This is used to deregister this event when the scope is destroyed.
+ * @param {Function} callBack Will be called when the event is emited. The function passes back the grid and an array of
+ * columns with sorts on them, in priority order.
+ *
+ * @example
+ *
+ * gridApi.core.on.sortChanged( $scope, function(grid, sortColumns){
+ * // do something
+ * });
+ *
+ */
+ self.api.registerEvent( 'core', 'sortChanged' );
+
+ /**
+ * @ngdoc function
+ * @name columnVisibilityChanged
+ * @methodOf ui.grid.core.api:PublicApi
+ * @description The visibility of a column has changed,
+ * the column itself is passed out as a parameter of the event.
+ *
+ * @param {$scope} scope The scope of the controller. This is used to deregister this event when the scope is destroyed.
+ * @param {Function} callBack Will be called when the event is emited. The function passes back the GridCol that has changed.
+ *
+ * @example
+ *
+ * gridApi.core.on.columnVisibilityChanged( $scope, function (column) {
+ * // do something
+ * } );
+ *
+ */
+ self.api.registerEvent( 'core', 'columnVisibilityChanged' );
+
+ /**
+ * @ngdoc method
+ * @name notifyDataChange
+ * @methodOf ui.grid.core.api:PublicApi
+ * @description Notify the grid that a data or config change has occurred,
+ * where that change isn't something the grid was otherwise noticing. This
+ * might be particularly relevant where you've changed values within the data
+ * and you'd like cell classes to be re-evaluated, or changed config within
+ * the columnDef and you'd like headerCellClasses to be re-evaluated.
+ * @param {string} type one of the
+ * {@link ui.grid.service:uiGridConstants#properties_dataChange uiGridConstants.dataChange}
+ * values (ALL, ROW, EDIT, COLUMN, OPTIONS), which tells us which refreshes to fire.
+ *
+ * - ALL: listeners fired on any of these events, fires listeners on all events.
+ * - ROW: fired when a row is added or removed.
+ * - EDIT: fired when the data in a cell is edited.
+ * - COLUMN: fired when the column definitions are modified.
+ * - OPTIONS: fired when the grid options are modified.
+ */
+ self.api.registerMethod( 'core', 'notifyDataChange', this.notifyDataChange );
+
+ /**
+ * @ngdoc method
+ * @name clearAllFilters
+ * @methodOf ui.grid.core.api:PublicApi
+ * @description Clears all filters and optionally refreshes the visible rows.
+ * @param {object} refreshRows Defaults to true.
+ * @param {object} clearConditions Defaults to false.
+ * @param {object} clearFlags Defaults to false.
+ * @returns {promise} If `refreshRows` is true, returns a promise of the rows refreshing.
+ */
+ self.api.registerMethod('core', 'clearAllFilters', this.clearAllFilters);
+
+ self.registerDataChangeCallback( self.columnRefreshCallback, [uiGridConstants.dataChange.COLUMN]);
+ self.registerDataChangeCallback( self.processRowsCallback, [uiGridConstants.dataChange.EDIT]);
+ self.registerDataChangeCallback( self.updateFooterHeightCallback, [uiGridConstants.dataChange.OPTIONS]);
+
+ self.registerStyleComputation({
+ priority: 10,
+ func: self.getFooterStyles
+ });
+ };
+
+ Grid.prototype.calcFooterHeight = function () {
+ if (!this.hasFooter()) {
+ return 0;
+ }
+
+ var height = 0;
+ if (this.options.showGridFooter) {
+ height += this.options.gridFooterHeight;
+ }
+
+ height += this.calcColumnFooterHeight();
+
+ return height;
+ };
+
+ Grid.prototype.calcColumnFooterHeight = function () {
+ var height = 0;
+
+ if (this.options.showColumnFooter) {
+ height += this.options.columnFooterHeight;
+ }
+
+ return height;
+ };
+
+ Grid.prototype.getFooterStyles = function () {
+ var style = '.grid' + this.id + ' .ui-grid-footer-aggregates-row { height: ' + this.options.columnFooterHeight + 'px; }';
+ style += ' .grid' + this.id + ' .ui-grid-footer-info { height: ' + this.options.gridFooterHeight + 'px; }';
+ return style;
+ };
+
+ Grid.prototype.hasFooter = function () {
+ return this.options.showGridFooter || this.options.showColumnFooter;
+ };
+
+ /**
+ * @ngdoc function
+ * @name isRTL
+ * @methodOf ui.grid.class:Grid
+ * @description Returns true if grid is RightToLeft
+ */
+ Grid.prototype.isRTL = function () {
+ return this.rtl;
+ };
+
+
+ /**
+ * @ngdoc function
+ * @name registerColumnBuilder
+ * @methodOf ui.grid.class:Grid
+ * @description When the build creates columns from column definitions, the columnbuilders will be called to add
+ * additional properties to the column.
+ * @param {function(colDef, col, gridOptions)} columnBuilder function to be called
+ */
+ Grid.prototype.registerColumnBuilder = function registerColumnBuilder(columnBuilder) {
+ this.columnBuilders.push(columnBuilder);
+ };
+
+ /**
+ * @ngdoc function
+ * @name buildColumnDefsFromData
+ * @methodOf ui.grid.class:Grid
+ * @description Populates columnDefs from the provided data
+ * @param {function(colDef, col, gridOptions)} rowBuilder function to be called
+ */
+ Grid.prototype.buildColumnDefsFromData = function (dataRows){
+ this.options.columnDefs = gridUtil.getColumnsFromData(dataRows, this.options.excludeProperties);
+ };
+
+ /**
+ * @ngdoc function
+ * @name registerRowBuilder
+ * @methodOf ui.grid.class:Grid
+ * @description When the build creates rows from gridOptions.data, the rowBuilders will be called to add
+ * additional properties to the row.
+ * @param {function(row, gridOptions)} rowBuilder function to be called
+ */
+ Grid.prototype.registerRowBuilder = function registerRowBuilder(rowBuilder) {
+ this.rowBuilders.push(rowBuilder);
+ };
+
+
+ /**
+ * @ngdoc function
+ * @name registerDataChangeCallback
+ * @methodOf ui.grid.class:Grid
+ * @description When a data change occurs, the data change callbacks of the specified type
+ * will be called. The rules are:
+ *
+ * - when the data watch fires, that is considered a ROW change (the data watch only notices
+ * added or removed rows)
+ * - when the api is called to inform us of a change, the declared type of that change is used
+ * - when a cell edit completes, the EDIT callbacks are triggered
+ * - when the columnDef watch fires, the COLUMN callbacks are triggered
+ * - when the options watch fires, the OPTIONS callbacks are triggered
+ *
+ * For a given event:
+ * - ALL calls ROW, EDIT, COLUMN, OPTIONS and ALL callbacks
+ * - ROW calls ROW and ALL callbacks
+ * - EDIT calls EDIT and ALL callbacks
+ * - COLUMN calls COLUMN and ALL callbacks
+ * - OPTIONS calls OPTIONS and ALL callbacks
+ *
+ * @param {function(grid)} callback function to be called
+ * @param {array} types the types of data change you want to be informed of. Values from
+ * the {@link ui.grid.service:uiGridConstants#properties_dataChange uiGridConstants.dataChange}
+ * values ( ALL, EDIT, ROW, COLUMN, OPTIONS ). Optional and defaults to ALL
+ * @returns {function} deregister function - a function that can be called to deregister this callback
+ */
+ Grid.prototype.registerDataChangeCallback = function registerDataChangeCallback(callback, types, _this) {
+ var uid = gridUtil.nextUid();
+ if ( !types ){
+ types = [uiGridConstants.dataChange.ALL];
+ }
+ if ( !Array.isArray(types)){
+ gridUtil.logError("Expected types to be an array or null in registerDataChangeCallback, value passed was: " + types );
+ }
+ this.dataChangeCallbacks[uid] = { callback: callback, types: types, _this:_this };
+
+ var self = this;
+ var deregisterFunction = function() {
+ delete self.dataChangeCallbacks[uid];
+ };
+ return deregisterFunction;
+ };
+
+ /**
+ * @ngdoc function
+ * @name callDataChangeCallbacks
+ * @methodOf ui.grid.class:Grid
+ * @description Calls the callbacks based on the type of data change that
+ * has occurred. Always calls the ALL callbacks, calls the ROW, EDIT, COLUMN and OPTIONS callbacks if the
+ * event type is matching, or if the type is ALL.
+ * @param {string} type the type of event that occurred - one of the
+ * {@link ui.grid.service:uiGridConstants#properties_dataChange uiGridConstants.dataChange}
+ * values (ALL, ROW, EDIT, COLUMN, OPTIONS)
+ */
+ Grid.prototype.callDataChangeCallbacks = function callDataChangeCallbacks(type, options) {
+ angular.forEach( this.dataChangeCallbacks, function( callback, uid ){
+ if ( callback.types.indexOf( uiGridConstants.dataChange.ALL ) !== -1 ||
+ callback.types.indexOf( type ) !== -1 ||
+ type === uiGridConstants.dataChange.ALL ) {
+ if (callback._this) {
+ callback.callback.apply(callback._this, this, options);
+ }
+ else {
+ callback.callback(this, options);
+ }
+ }
+ }, this);
+ };
+
+ /**
+ * @ngdoc function
+ * @name notifyDataChange
+ * @methodOf ui.grid.class:Grid
+ * @description Notifies us that a data change has occurred, used in the public
+ * api for users to tell us when they've changed data or some other event that
+ * our watches cannot pick up
+ * @param {string} type the type of event that occurred - one of the
+ * uiGridConstants.dataChange values (ALL, ROW, EDIT, COLUMN, OPTIONS)
+ *
+ * - ALL: listeners fired on any of these events, fires listeners on all events.
+ * - ROW: fired when a row is added or removed.
+ * - EDIT: fired when the data in a cell is edited.
+ * - COLUMN: fired when the column definitions are modified.
+ * - OPTIONS: fired when the grid options are modified.
+ */
+ Grid.prototype.notifyDataChange = function notifyDataChange(type) {
+ var constants = uiGridConstants.dataChange;
+ if ( type === constants.ALL ||
+ type === constants.COLUMN ||
+ type === constants.EDIT ||
+ type === constants.ROW ||
+ type === constants.OPTIONS ){
+ this.callDataChangeCallbacks( type );
+ } else {
+ gridUtil.logError("Notified of a data change, but the type was not recognised, so no action taken, type was: " + type);
+ }
+ };
+
+
+ /**
+ * @ngdoc function
+ * @name columnRefreshCallback
+ * @methodOf ui.grid.class:Grid
+ * @description refreshes the grid when a column refresh
+ * is notified, which triggers handling of the visible flag.
+ * This is called on uiGridConstants.dataChange.COLUMN, and is
+ * registered as a dataChangeCallback in grid.js
+ * @param {object} grid The grid object.
+ * @param {object} options Any options passed into the callback.
+ */
+ Grid.prototype.columnRefreshCallback = function columnRefreshCallback(grid, options){
+ grid.buildColumns(options);
+ grid.queueGridRefresh();
+ };
+
+
+ /**
+ * @ngdoc function
+ * @name processRowsCallback
+ * @methodOf ui.grid.class:Grid
+ * @description calls the row processors, specifically
+ * intended to reset the sorting when an edit is called,
+ * registered as a dataChangeCallback on uiGridConstants.dataChange.EDIT
+ * @param {string} name column name
+ */
+ Grid.prototype.processRowsCallback = function processRowsCallback( grid ){
+ grid.queueGridRefresh();
+ };
+
+
+ /**
+ * @ngdoc function
+ * @name updateFooterHeightCallback
+ * @methodOf ui.grid.class:Grid
+ * @description recalculates the footer height,
+ * registered as a dataChangeCallback on uiGridConstants.dataChange.OPTIONS
+ * @param {string} name column name
+ */
+ Grid.prototype.updateFooterHeightCallback = function updateFooterHeightCallback( grid ){
+ grid.footerHeight = grid.calcFooterHeight();
+ grid.columnFooterHeight = grid.calcColumnFooterHeight();
+ };
+
+
+ /**
+ * @ngdoc function
+ * @name getColumn
+ * @methodOf ui.grid.class:Grid
+ * @description returns a grid column for the column name
+ * @param {string} name column name
+ */
+ Grid.prototype.getColumn = function getColumn(name) {
+ var columns = this.columns.filter(function (column) {
+ return column.colDef.name === name;
+ });
+ return columns.length > 0 ? columns[0] : null;
+ };
+
+ /**
+ * @ngdoc function
+ * @name getColDef
+ * @methodOf ui.grid.class:Grid
+ * @description returns a grid colDef for the column name
+ * @param {string} name column.field
+ */
+ Grid.prototype.getColDef = function getColDef(name) {
+ var colDefs = this.options.columnDefs.filter(function (colDef) {
+ return colDef.name === name;
+ });
+ return colDefs.length > 0 ? colDefs[0] : null;
+ };
+
+ /**
+ * @ngdoc function
+ * @name assignTypes
+ * @methodOf ui.grid.class:Grid
+ * @description uses the first row of data to assign colDef.type for any types not defined.
+ */
+ /**
+ * @ngdoc property
+ * @name type
+ * @propertyOf ui.grid.class:GridOptions.columnDef
+ * @description the type of the column, used in sorting. If not provided then the
+ * grid will guess the type. Add this only if the grid guessing is not to your
+ * satisfaction. One of:
+ * - 'string'
+ * - 'boolean'
+ * - 'number'
+ * - 'date'
+ * - 'object'
+ * - 'numberStr'
+ * Note that if you choose date, your dates should be in a javascript date type
+ *
+ */
+ Grid.prototype.assignTypes = function(){
+ var self = this;
+ self.options.columnDefs.forEach(function (colDef, index) {
+
+ //Assign colDef type if not specified
+ if (!colDef.type) {
+ var col = new GridColumn(colDef, index, self);
+ var firstRow = self.rows.length > 0 ? self.rows[0] : null;
+ if (firstRow) {
+ colDef.type = gridUtil.guessType(self.getCellValue(firstRow, col));
+ }
+ else {
+ colDef.type = 'string';
+ }
+ }
+ });
+ };
+
+
+ /**
+ * @ngdoc function
+ * @name isRowHeaderColumn
+ * @methodOf ui.grid.class:Grid
+ * @description returns true if the column is a row Header
+ * @param {object} column column
+ */
+ Grid.prototype.isRowHeaderColumn = function isRowHeaderColumn(column) {
+ return this.rowHeaderColumns.indexOf(column) !== -1;
+ };
+
+ /**
+ * @ngdoc function
+ * @name addRowHeaderColumn
+ * @methodOf ui.grid.class:Grid
+ * @description adds a row header column to the grid
+ * @param {object} colDef Column definition object.
+ * @param {float} order Number that indicates where the column should be placed in the grid.
+ * @param {boolean} stopColumnBuild Prevents the buildColumn callback from being triggered. This is useful to improve
+ * performance of the grid during initial load.
+ */
+ Grid.prototype.addRowHeaderColumn = function addRowHeaderColumn(colDef, order, stopColumnBuild) {
+ var self = this;
+
+ //default order
+ if (order === undefined) {
+ order = 0;
+ }
+
+ var rowHeaderCol = new GridColumn(colDef, gridUtil.nextUid(), self);
+ rowHeaderCol.isRowHeader = true;
+ if (self.isRTL()) {
+ self.createRightContainer();
+ rowHeaderCol.renderContainer = 'right';
+ }
+ else {
+ self.createLeftContainer();
+ rowHeaderCol.renderContainer = 'left';
+ }
+
+ // relies on the default column builder being first in array, as it is instantiated
+ // as part of grid creation
+ self.columnBuilders[0](colDef,rowHeaderCol,self.options)
+ .then(function(){
+ rowHeaderCol.enableFiltering = false;
+ rowHeaderCol.enableSorting = false;
+ rowHeaderCol.enableHiding = false;
+ rowHeaderCol.headerPriority = order;
+ self.rowHeaderColumns.push(rowHeaderCol);
+ self.rowHeaderColumns = self.rowHeaderColumns.sort(function (a, b) {
+ return a.headerPriority - b.headerPriority;
+ });
+
+ if (!stopColumnBuild) {
+ self.buildColumns()
+ .then(function() {
+ self.preCompileCellTemplates();
+ self.queueGridRefresh();
+ }).catch(angular.noop);
+ }
+ }).catch(angular.noop);
+ };
+
+ /**
+ * @ngdoc function
+ * @name getOnlyDataColumns
+ * @methodOf ui.grid.class:Grid
+ * @description returns all columns except for rowHeader columns
+ */
+ Grid.prototype.getOnlyDataColumns = function getOnlyDataColumns() {
+ var self = this;
+ var cols = [];
+ self.columns.forEach(function (col) {
+ if (self.rowHeaderColumns.indexOf(col) === -1) {
+ cols.push(col);
+ }
+ });
+ return cols;
+ };
+
+ /**
+ * @ngdoc function
+ * @name buildColumns
+ * @methodOf ui.grid.class:Grid
+ * @description creates GridColumn objects from the columnDefinition. Calls each registered
+ * columnBuilder to further process the column
+ * @param {object} options An object contains options to use when building columns
+ *
+ * * **orderByColumnDefs**: defaults to **false**. When true, `buildColumns` will reorder existing columns according to the order within the column definitions.
+ *
+ * @returns {Promise} a promise to load any needed column resources
+ */
+ Grid.prototype.buildColumns = function buildColumns(opts) {
+ var options = {
+ orderByColumnDefs: false
+ };
+
+ angular.extend(options, opts);
+
+ // gridUtil.logDebug('buildColumns');
+ var self = this;
+ var builderPromises = [];
+ var headerOffset = self.rowHeaderColumns.length;
+ var i;
+
+ // Remove any columns for which a columnDef cannot be found
+ // Deliberately don't use forEach, as it doesn't like splice being called in the middle
+ // Also don't cache columns.length, as it will change during this operation
+ for (i = 0; i < self.columns.length; i++){
+ if (!self.getColDef(self.columns[i].name)) {
+ self.columns.splice(i, 1);
+ i--;
+ }
+ }
+
+ //add row header columns to the grid columns array _after_ columns without columnDefs have been removed
+ //rowHeaderColumns is ordered by priority so insert in reverse
+ for (var j = self.rowHeaderColumns.length - 1; j >= 0; j--) {
+ self.columns.unshift(self.rowHeaderColumns[j]);
+ }
+
+
+
+ // look at each column def, and update column properties to match. If the column def
+ // doesn't have a column, then splice in a new gridCol
+ self.options.columnDefs.forEach(function (colDef, index) {
+ self.preprocessColDef(colDef);
+ var col = self.getColumn(colDef.name);
+
+ if (!col) {
+ col = new GridColumn(colDef, gridUtil.nextUid(), self);
+ self.columns.splice(index + headerOffset, 0, col);
+ }
+ else {
+ // tell updateColumnDef that the column was pre-existing
+ col.updateColumnDef(colDef, false);
+ }
+
+ self.columnBuilders.forEach(function (builder) {
+ builderPromises.push(builder.call(self, colDef, col, self.options));
+ });
+ });
+
+ /*** Reorder columns if necessary ***/
+ if (!!options.orderByColumnDefs) {
+ // Create a shallow copy of the columns as a cache
+ var columnCache = self.columns.slice(0);
+
+ // We need to allow for the "row headers" when mapping from the column defs array to the columns array
+ // If we have a row header in columns[0] and don't account for it we'll overwrite it with the column in columnDefs[0]
+
+ // Go through all the column defs, use the shorter of columns length and colDefs.length because if a user has given two columns the same name then
+ // columns will be shorter than columnDefs. In this situation we'll avoid an error, but the user will still get an unexpected result
+ var len = Math.min(self.options.columnDefs.length, self.columns.length);
+ for (i = 0; i < len; i++) {
+ // If the column at this index has a different name than the column at the same index in the column defs...
+ if (self.columns[i + headerOffset].name !== self.options.columnDefs[i].name) {
+ // Replace the one in the cache with the appropriate column
+ columnCache[i + headerOffset] = self.getColumn(self.options.columnDefs[i].name);
+ }
+ else {
+ // Otherwise just copy over the one from the initial columns
+ columnCache[i + headerOffset] = self.columns[i + headerOffset];
+ }
+ }
+
+ // Empty out the columns array, non-destructively
+ self.columns.length = 0;
+
+ // And splice in the updated, ordered columns from the cache
+ Array.prototype.splice.apply(self.columns, [0, 0].concat(columnCache));
+ }
+
+ return $q.all(builderPromises).then(function(){
+ if (self.rows.length > 0){
+ self.assignTypes();
+ }
+ if (options.preCompileCellTemplates) {
+ self.preCompileCellTemplates();
+ }
+ }).catch(angular.noop);
+ };
+
+ Grid.prototype.preCompileCellTemplate = function(col) {
+ var self = this;
+ var html = col.cellTemplate.replace(uiGridConstants.MODEL_COL_FIELD, self.getQualifiedColField(col));
+ html = html.replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)');
+
+ col.compiledElementFn = $compile(html);
+
+ if (col.compiledElementFnDefer) {
+ col.compiledElementFnDefer.resolve(col.compiledElementFn);
+ }
+ };
+
+/**
+ * @ngdoc function
+ * @name preCompileCellTemplates
+ * @methodOf ui.grid.class:Grid
+ * @description precompiles all cell templates
+ */
+ Grid.prototype.preCompileCellTemplates = function() {
+ var self = this;
+ self.columns.forEach(function (col) {
+ if ( col.cellTemplate ){
+ self.preCompileCellTemplate( col );
+ } else if ( col.cellTemplatePromise ){
+ col.cellTemplatePromise.then( function() {
+ self.preCompileCellTemplate( col );
+ }).catch(angular.noop);
+ }
+ });
+ };
+
+ /**
+ * @ngdoc function
+ * @name getGridQualifiedColField
+ * @methodOf ui.grid.class:Grid
+ * @description Returns the $parse-able accessor for a column within its $scope
+ * @param {GridColumn} col col object
+ */
+ Grid.prototype.getQualifiedColField = function (col) {
+ var base = 'row.entity';
+ if ( col.field === uiGridConstants.ENTITY_BINDING ) {
+ return base;
+ }
+ return gridUtil.preEval(base + '.' + col.field);
+ };
+
+ /**
+ * @ngdoc function
+ * @name createLeftContainer
+ * @methodOf ui.grid.class:Grid
+ * @description creates the left render container if it doesn't already exist
+ */
+ Grid.prototype.createLeftContainer = function() {
+ if (!this.hasLeftContainer()) {
+ this.renderContainers.left = new GridRenderContainer('left', this, { disableColumnOffset: true });
+ }
+ };
+
+ /**
+ * @ngdoc function
+ * @name createRightContainer
+ * @methodOf ui.grid.class:Grid
+ * @description creates the right render container if it doesn't already exist
+ */
+ Grid.prototype.createRightContainer = function() {
+ if (!this.hasRightContainer()) {
+ this.renderContainers.right = new GridRenderContainer('right', this, { disableColumnOffset: true });
+ }
+ };
+
+ /**
+ * @ngdoc function
+ * @name hasLeftContainer
+ * @methodOf ui.grid.class:Grid
+ * @description returns true if leftContainer exists
+ */
+ Grid.prototype.hasLeftContainer = function() {
+ return this.renderContainers.left !== undefined;
+ };
+
+ /**
+ * @ngdoc function
+ * @name hasRightContainer
+ * @methodOf ui.grid.class:Grid
+ * @description returns true if rightContainer exists
+ */
+ Grid.prototype.hasRightContainer = function() {
+ return this.renderContainers.right !== undefined;
+ };
+
+
+ /**
+ * undocumented function
+ * @name preprocessColDef
+ * @methodOf ui.grid.class:Grid
+ * @description defaults the name property from field to maintain backwards compatibility with 2.x
+ * validates that name or field is present
+ */
+ Grid.prototype.preprocessColDef = function preprocessColDef(colDef) {
+ var self = this;
+
+ if (!colDef.field && !colDef.name) {
+ throw new Error('colDef.name or colDef.field property is required');
+ }
+
+ //maintain backwards compatibility with 2.x
+ //field was required in 2.x. now name is required
+ if (colDef.name === undefined && colDef.field !== undefined) {
+ // See if the column name already exists:
+ var newName = colDef.field,
+ counter = 2;
+ while (self.getColumn(newName)) {
+ newName = colDef.field + counter.toString();
+ counter++;
+ }
+ colDef.name = newName;
+ }
+ };
+
+ // Return a list of items that exist in the `n` array but not the `o` array. Uses optional property accessors passed as third & fourth parameters
+ Grid.prototype.newInN = function newInN(o, n, oAccessor, nAccessor) {
+ var self = this;
+
+ var t = [];
+ for (var i = 0; i < n.length; i++) {
+ var nV = nAccessor ? n[i][nAccessor] : n[i];
+
+ var found = false;
+ for (var j = 0; j < o.length; j++) {
+ var oV = oAccessor ? o[j][oAccessor] : o[j];
+ if (self.options.rowEquality(nV, oV)) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ t.push(nV);
+ }
+ }
+
+ return t;
+ };
+
+ /**
+ * @ngdoc function
+ * @name getRow
+ * @methodOf ui.grid.class:Grid
+ * @description returns the GridRow that contains the rowEntity
+ * @param {object} rowEntity the gridOptions.data array element instance
+ * @param {array} lookInRows [optional] the rows to look in - if not provided then
+ * looks in grid.rows
+ */
+ Grid.prototype.getRow = function getRow(rowEntity, lookInRows) {
+ var self = this;
+
+ lookInRows = typeof(lookInRows) === 'undefined' ? self.rows : lookInRows;
+
+ var rows = lookInRows.filter(function (row) {
+ return self.options.rowEquality(row.entity, rowEntity);
+ });
+ return rows.length > 0 ? rows[0] : null;
+ };
+
+
+ /**
+ * @ngdoc function
+ * @name modifyRows
+ * @methodOf ui.grid.class:Grid
+ * @description creates or removes GridRow objects from the newRawData array. Calls each registered
+ * rowBuilder to further process the row
+ * @param {array} newRawData Modified set of data
+ *
+ * This method aims to achieve three things:
+ * 1. the resulting rows array is in the same order as the newRawData, we'll call
+ * rowsProcessors immediately after to sort the data anyway
+ * 2. if we have row hashing available, we try to use the rowHash to find the row
+ * 3. no memory leaks - rows that are no longer in newRawData need to be garbage collected
+ *
+ * The basic logic flow makes use of the newRawData, oldRows and oldHash, and creates
+ * the newRows and newHash
+ *
+ * ```
+ * newRawData.forEach newEntity
+ * if (hashing enabled)
+ * check oldHash for newEntity
+ * else
+ * look for old row directly in oldRows
+ * if !oldRowFound // must be a new row
+ * create newRow
+ * append to the newRows and add to newHash
+ * run the processors
+ * ```
+ *
+ * Rows are identified using the hashKey if configured. If not configured, then rows
+ * are identified using the gridOptions.rowEquality function
+ *
+ * This method is useful when trying to select rows immediately after loading data without
+ * using a $timeout/$interval, e.g.:
+ *
+ * $scope.gridOptions.data = someData;
+ * $scope.gridApi.grid.modifyRows($scope.gridOptions.data);
+ * $scope.gridApi.selection.selectRow($scope.gridOptions.data[0]);
+ *
+ * OR to persist row selection after data update (e.g. rows selected, new data loaded, want
+ * originally selected rows to be re-selected))
+ */
+ Grid.prototype.modifyRows = function modifyRows(newRawData) {
+ var self = this;
+ var oldRows = self.rows.slice(0);
+ var oldRowHash = self.rowHashMap || self.createRowHashMap();
+ var allRowsSelected = true;
+ self.rowHashMap = self.createRowHashMap();
+ self.rows.length = 0;
+
+ newRawData.forEach( function( newEntity, i ) {
+ var newRow, oldRow;
+
+ if ( self.options.enableRowHashing ){
+ // if hashing is enabled, then this row will be in the hash if we already know about it
+ oldRow = oldRowHash.get( newEntity );
+ } else {
+ // otherwise, manually search the oldRows to see if we can find this row
+ oldRow = self.getRow(newEntity, oldRows);
+ }
+
+ // update newRow to have an entity
+ if ( oldRow ) {
+ newRow = oldRow;
+ newRow.entity = newEntity;
+ }
+
+ // if we didn't find the row, it must be new, so create it
+ if ( !newRow ){
+ newRow = self.processRowBuilders(new GridRow(newEntity, i, self));
+ }
+
+ self.rows.push( newRow );
+ self.rowHashMap.put( newEntity, newRow );
+ if (!newRow.isSelected) {
+ allRowsSelected = false;
+ }
+ });
+
+ if (self.selection && self.rows.length) {
+ self.selection.selectAll = allRowsSelected;
+ }
+
+ self.assignTypes();
+
+ var p1 = $q.when(self.processRowsProcessors(self.rows))
+ .then(function (renderableRows) {
+ return self.setVisibleRows(renderableRows);
+ }).catch(angular.noop);
+
+ var p2 = $q.when(self.processColumnsProcessors(self.columns))
+ .then(function (renderableColumns) {
+ return self.setVisibleColumns(renderableColumns);
+ }).catch(angular.noop);
+
+ return $q.all([p1, p2]);
+ };
+
+
+ /**
+ * Private Undocumented Method
+ * @name addRows
+ * @methodOf ui.grid.class:Grid
+ * @description adds the newRawData array of rows to the grid and calls all registered
+ * rowBuilders. this keyword will reference the grid
+ */
+ Grid.prototype.addRows = function addRows(newRawData) {
+ var self = this;
+
+ var existingRowCount = self.rows.length;
+ for (var i = 0; i < newRawData.length; i++) {
+ var newRow = self.processRowBuilders(new GridRow(newRawData[i], i + existingRowCount, self));
+
+ if (self.options.enableRowHashing) {
+ var found = self.rowHashMap.get(newRow.entity);
+ if (found) {
+ found.row = newRow;
+ }
+ }
+
+ self.rows.push(newRow);
+ }
+ };
+
+ /**
+ * @ngdoc function
+ * @name processRowBuilders
+ * @methodOf ui.grid.class:Grid
+ * @description processes all RowBuilders for the gridRow
+ * @param {GridRow} gridRow reference to gridRow
+ * @returns {GridRow} the gridRow with all additional behavior added
+ */
+ Grid.prototype.processRowBuilders = function processRowBuilders(gridRow) {
+ var self = this;
+
+ self.rowBuilders.forEach(function (builder) {
+ builder.call(self, gridRow, self.options);
+ });
+
+ return gridRow;
+ };
+
+ /**
+ * @ngdoc function
+ * @name registerStyleComputation
+ * @methodOf ui.grid.class:Grid
+ * @description registered a styleComputation function
+ *
+ * If the function returns a value it will be appended into the grid's `
"}),n.trustAsHtml("
+ * gridApi.colMovable.on.columnPositionChanged(scope,function(colDef, originalPosition, newPosition){})
+ *
+ * @param {object} colDef the column that was moved
+ * @param {integer} originalPosition of the column
+ * @param {integer} finalPosition of the column
+ */
+ colMovable: {
+ columnPositionChanged: function (colDef, originalPosition, newPosition) {
+ }
+ }
+ },
+ methods: {
+ /**
+ * @ngdoc method
+ * @name moveColumn
+ * @methodOf ui.grid.moveColumns.api:PublicApi
+ * @description Method can be used to change column position.
+ *
+ * gridApi.colMovable.moveColumn(oldPosition, newPosition)
+ *
+ * @param {integer} originalPosition of the column
+ * @param {integer} finalPosition of the column
+ */
+ colMovable: {
+ moveColumn: function (originalPosition, finalPosition) {
+ var columns = grid.columns;
+ if (!angular.isNumber(originalPosition) || !angular.isNumber(finalPosition)) {
+ gridUtil.logError('MoveColumn: Please provide valid values for originalPosition and finalPosition');
+ return;
+ }
+ var nonMovableColumns = 0;
+ for (var i = 0; i < columns.length; i++) {
+ if ((angular.isDefined(columns[i].colDef.visible) && columns[i].colDef.visible === false) || columns[i].isRowHeader === true) {
+ nonMovableColumns++;
+ }
+ }
+ if (originalPosition >= (columns.length - nonMovableColumns) || finalPosition >= (columns.length - nonMovableColumns)) {
+ gridUtil.logError('MoveColumn: Invalid values for originalPosition, finalPosition');
+ return;
+ }
+ var findPositionForRenderIndex = function (index) {
+ var position = index;
+ for (var i = 0; i <= position; i++) {
+ if (angular.isDefined(columns[i]) && ((angular.isDefined(columns[i].colDef.visible) && columns[i].colDef.visible === false) || columns[i].isRowHeader === true)) {
+ position++;
+ }
+ }
+ return position;
+ };
+ self.redrawColumnAtPosition(grid, findPositionForRenderIndex(originalPosition), findPositionForRenderIndex(finalPosition));
+ }
+ }
+ }
+ };
+ grid.api.registerEventsFromObject(publicApi.events);
+ grid.api.registerMethodsFromObject(publicApi.methods);
+ },
+ defaultGridOptions: function (gridOptions) {
+ /**
+ * @ngdoc object
+ * @name ui.grid.moveColumns.api:GridOptions
+ *
+ * @description Options for configuring the move column feature, these are available to be
+ * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
+ */
+ /**
+ * @ngdoc object
+ * @name enableColumnMoving
+ * @propertyOf ui.grid.moveColumns.api:GridOptions
+ * @description If defined, sets the default value for the colMovable flag on each individual colDefs
+ * if their individual enableColumnMoving configuration is not defined. Defaults to true.
+ */
+ gridOptions.enableColumnMoving = gridOptions.enableColumnMoving !== false;
+ },
+ movableColumnBuilder: function (colDef, col, gridOptions) {
+ var promises = [];
+ /**
+ * @ngdoc object
+ * @name ui.grid.moveColumns.api:ColumnDef
+ *
+ * @description Column Definition for move column feature, these are available to be
+ * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
+ */
+ /**
+ * @ngdoc object
+ * @name enableColumnMoving
+ * @propertyOf ui.grid.moveColumns.api:ColumnDef
+ * @description Enable column moving for the column.
+ */
+ colDef.enableColumnMoving = colDef.enableColumnMoving === undefined ? gridOptions.enableColumnMoving
+ : colDef.enableColumnMoving;
+ return $q.all(promises);
+ },
+ /**
+ * @ngdoc method
+ * @name updateColumnCache
+ * @methodOf ui.grid.moveColumns
+ * @description Cache the current order of columns, so we can restore them after new columnDefs are defined
+ */
+ updateColumnCache: function(grid){
+ grid.moveColumns.orderCache = grid.getOnlyDataColumns();
+ },
+ /**
+ * @ngdoc method
+ * @name verifyColumnOrder
+ * @methodOf ui.grid.moveColumns
+ * @description dataChangeCallback which uses the cached column order to restore the column order
+ * when it is reset by altering the columnDefs array.
+ */
+ verifyColumnOrder: function(grid){
+ var headerRowOffset = grid.rowHeaderColumns.length;
+ var newIndex;
+
+ angular.forEach(grid.moveColumns.orderCache, function(cacheCol, cacheIndex){
+ newIndex = grid.columns.indexOf(cacheCol);
+ if ( newIndex !== -1 && newIndex - headerRowOffset !== cacheIndex ){
+ var column = grid.columns.splice(newIndex, 1)[0];
+ grid.columns.splice(cacheIndex + headerRowOffset, 0, column);
+ }
+ });
+ },
+ redrawColumnAtPosition: function (grid, originalPosition, newPosition) {
+ var columns = grid.columns;
+
+ if (originalPosition === newPosition) {
+ return;
+ }
+
+ //check columns in between move-range to make sure they are visible columns
+ var pos = (originalPosition < newPosition) ? originalPosition + 1 : originalPosition - 1;
+ var i0 = Math.min(pos, newPosition);
+ for (i0; i0 <= Math.max(pos, newPosition); i0++) {
+ if (columns[i0].visible) {
+ break;
+ }
+ }
+ if (i0 > Math.max(pos, newPosition)) {
+ //no visible column found, column did not visibly move
+ return;
+ }
+
+ var originalColumn = columns[originalPosition];
+ if (originalColumn.colDef.enableColumnMoving) {
+ if (originalPosition > newPosition) {
+ for (var i1 = originalPosition; i1 > newPosition; i1--) {
+ columns[i1] = columns[i1 - 1];
+ }
+ }
+ else if (newPosition > originalPosition) {
+ for (var i2 = originalPosition; i2 < newPosition; i2++) {
+ columns[i2] = columns[i2 + 1];
+ }
+ }
+ columns[newPosition] = originalColumn;
+ service.updateColumnCache(grid);
+ grid.queueGridRefresh();
+ $rootScope.$applyAsync(function () {
+ grid.api.core.notifyDataChange( uiGridConstants.dataChange.COLUMN );
+ grid.api.colMovable.raise.columnPositionChanged(originalColumn.colDef, originalPosition, newPosition);
+ });
+ }
+ }
+ };
+ return service;
+ }]);
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.moveColumns.directive:uiGridMoveColumns
+ * @element div
+ * @restrict A
+ * @description Adds column moving features to the ui-grid directive.
+ * @example
+
+ * gridApi.pinning.on.columnPinned(scope, function(colDef){})
+ *
+ * @param {object} colDef the column that was changed
+ * @param {string} container the render container the column is in ('left', 'right', '')
+ */
+ columnPinned: function(colDef, container) {
+ }
+ }
+ },
+ methods: {
+ pinning: {
+ /**
+ * @ngdoc function
+ * @name pinColumn
+ * @methodOf ui.grid.pinning.api:PublicApi
+ * @description pin column left, right, or none
+ *
+ * gridApi.pinning.pinColumn(col, uiGridPinningConstants.container.LEFT)
+ *
+ * @param {gridColumn} col the column being pinned
+ * @param {string} container one of the recognised types
+ * from uiGridPinningConstants
+ */
+ pinColumn: function(col, container) {
+ service.pinColumn(grid, col, container);
+ }
+ }
+ }
+ };
+
+ grid.api.registerEventsFromObject(publicApi.events);
+ grid.api.registerMethodsFromObject(publicApi.methods);
+ },
+
+ defaultGridOptions: function (gridOptions) {
+ //default option to true unless it was explicitly set to false
+ /**
+ * @ngdoc object
+ * @name ui.grid.pinning.api:GridOptions
+ *
+ * @description GridOptions for pinning feature, these are available to be
+ * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
+ */
+
+ /**
+ * @ngdoc object
+ * @name enablePinning
+ * @propertyOf ui.grid.pinning.api:GridOptions
+ * @description Enable pinning for the entire grid.
+ *
Defaults to true
+ */
+ gridOptions.enablePinning = gridOptions.enablePinning !== false;
+ /**
+ * @ngdoc object
+ * @name hidePinLeft
+ * @propertyOf ui.grid.pinning.api:GridOptions
+ * @description Hide Pin Left for the entire grid.
+ *
Defaults to false
+ */
+ gridOptions.hidePinLeft = gridOptions.enablePinning && gridOptions.hidePinLeft;
+ /**
+ * @ngdoc object
+ * @name hidePinRight
+ * @propertyOf ui.grid.pinning.api:GridOptions
+ * @description Hide Pin Right pinning for the entire grid.
+ *
Defaults to false
+ */
+ gridOptions.hidePinRight = gridOptions.enablePinning && gridOptions.hidePinRight;
+ },
+
+ pinningColumnBuilder: function (colDef, col, gridOptions) {
+ //default to true unless gridOptions or colDef is explicitly false
+
+ /**
+ * @ngdoc object
+ * @name ui.grid.pinning.api:ColumnDef
+ *
+ * @description ColumnDef for pinning feature, these are available to be
+ * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
+ */
+
+ /**
+ * @ngdoc object
+ * @name enablePinning
+ * @propertyOf ui.grid.pinning.api:ColumnDef
+ * @description Enable pinning for the individual column.
+ *
Defaults to true
+ */
+ colDef.enablePinning = colDef.enablePinning === undefined ? gridOptions.enablePinning : colDef.enablePinning;
+ /**
+ * @ngdoc object
+ * @name hidePinLeft
+ * @propertyOf ui.grid.pinning.api:ColumnDef
+ * @description Hide Pin Left for the individual column.
+ *
Defaults to false
+ */
+ colDef.hidePinLeft = colDef.hidePinLeft === undefined ? gridOptions.hidePinLeft : colDef.hidePinLeft;
+ /**
+ * @ngdoc object
+ * @name hidePinRight
+ * @propertyOf ui.grid.pinning.api:ColumnDef
+ * @description Hide Pin Right for the individual column.
+ *
Defaults to false
+ */
+ colDef.hidePinRight = colDef.hidePinRight === undefined ? gridOptions.hidePinRight : colDef.hidePinRight;
+
+ /**
+ * @ngdoc object
+ * @name pinnedLeft
+ * @propertyOf ui.grid.pinning.api:ColumnDef
+ * @description Column is pinned left when grid is rendered
+ *
Defaults to false
+ */
+
+ /**
+ * @ngdoc object
+ * @name pinnedRight
+ * @propertyOf ui.grid.pinning.api:ColumnDef
+ * @description Column is pinned right when grid is rendered
+ *
Defaults to false
+ */
+ if (colDef.pinnedLeft) {
+ col.renderContainer = 'left';
+ col.grid.createLeftContainer();
+ }
+ else if (colDef.pinnedRight) {
+ col.renderContainer = 'right';
+ col.grid.createRightContainer();
+ }
+
+ if (!colDef.enablePinning) {
+ return;
+ }
+
+ var pinColumnLeftAction = {
+ name: 'ui.grid.pinning.pinLeft',
+ title: i18nService.get().pinning.pinLeft,
+ icon: 'ui-grid-icon-left-open',
+ shown: function () {
+ return typeof(this.context.col.renderContainer) === 'undefined' || !this.context.col.renderContainer || this.context.col.renderContainer !== 'left';
+ },
+ action: function () {
+ service.pinColumn(this.context.col.grid, this.context.col, uiGridPinningConstants.container.LEFT);
+ }
+ };
+
+ var pinColumnRightAction = {
+ name: 'ui.grid.pinning.pinRight',
+ title: i18nService.get().pinning.pinRight,
+ icon: 'ui-grid-icon-right-open',
+ shown: function () {
+ return typeof(this.context.col.renderContainer) === 'undefined' || !this.context.col.renderContainer || this.context.col.renderContainer !== 'right';
+ },
+ action: function () {
+ service.pinColumn(this.context.col.grid, this.context.col, uiGridPinningConstants.container.RIGHT);
+ }
+ };
+
+ var removePinAction = {
+ name: 'ui.grid.pinning.unpin',
+ title: i18nService.get().pinning.unpin,
+ icon: 'ui-grid-icon-cancel',
+ shown: function () {
+ return typeof(this.context.col.renderContainer) !== 'undefined' && this.context.col.renderContainer !== null && this.context.col.renderContainer !== 'body';
+ },
+ action: function () {
+ service.pinColumn(this.context.col.grid, this.context.col, uiGridPinningConstants.container.NONE);
+ }
+ };
+
+ //// Skip from menu if hidePinLeft or hidePinRight is true
+ if (!colDef.hidePinLeft && !gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.pinning.pinLeft')) {
+ col.menuItems.push(pinColumnLeftAction);
+ }
+ if (!colDef.hidePinRight && !gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.pinning.pinRight')) {
+ col.menuItems.push(pinColumnRightAction);
+ }
+ if (!gridUtil.arrayContainsObjectWithProperty(col.menuItems, 'name', 'ui.grid.pinning.unpin')) {
+ col.menuItems.push(removePinAction);
+ }
+ },
+
+ pinColumn: function(grid, col, container) {
+ if (container === uiGridPinningConstants.container.NONE) {
+ col.renderContainer = null;
+ col.colDef.pinnedLeft = col.colDef.pinnedRight = false;
+ }
+ else {
+ col.renderContainer = container;
+ if (container === uiGridPinningConstants.container.LEFT) {
+ grid.createLeftContainer();
+ }
+ else if (container === uiGridPinningConstants.container.RIGHT) {
+ grid.createRightContainer();
+ }
+ }
+
+ grid.refresh()
+ .then(function() {
+ grid.api.pinning.raise.columnPinned( col.colDef, container );
+ });
+ }
+ };
+
+ return service;
+ }]);
+
+ module.directive('uiGridPinning', ['gridUtil', 'uiGridPinningService',
+ function (gridUtil, uiGridPinningService) {
+ return {
+ require: 'uiGrid',
+ scope: false,
+ compile: function () {
+ return {
+ pre: function ($scope, $elm, $attrs, uiGridCtrl) {
+ uiGridPinningService.initializeGrid(uiGridCtrl.grid);
+ },
+ post: function ($scope, $elm, $attrs, uiGridCtrl) {
+ }
+ };
+ }
+ };
+ }]);
+
+
+})();
diff --git a/release/4.4.11/ui-grid.pinning.min.js b/release/4.4.11/ui-grid.pinning.min.js
new file mode 100644
index 000000000..ea3df2511
--- /dev/null
+++ b/release/4.4.11/ui-grid.pinning.min.js
@@ -0,0 +1,7 @@
+/*!
+ * ui-grid - v4.4.11 - 2018-05-16
+ * Copyright (c) 2018 ; License: MIT
+ */
+
+
+!function(){"use strict";var n=angular.module("ui.grid.pinning",["ui.grid"]);n.constant("uiGridPinningConstants",{container:{LEFT:"left",RIGHT:"right",NONE:""}}),n.service("uiGridPinningService",["gridUtil","GridRenderContainer","i18nService","uiGridPinningConstants",function(c,n,d,u){var a={initializeGrid:function(e){a.defaultGridOptions(e.options),e.registerColumnBuilder(a.pinningColumnBuilder);var n={events:{pinning:{columnPinned:function(n,i){}}},methods:{pinning:{pinColumn:function(n,i){a.pinColumn(e,n,i)}}}};e.api.registerEventsFromObject(n.events),e.api.registerMethodsFromObject(n.methods)},defaultGridOptions:function(n){n.enablePinning=!1!==n.enablePinning,n.hidePinLeft=n.enablePinning&&n.hidePinLeft,n.hidePinRight=n.enablePinning&&n.hidePinRight},pinningColumnBuilder:function(n,i,e){if(n.enablePinning=void 0===n.enablePinning?e.enablePinning:n.enablePinning,n.hidePinLeft=void 0===n.hidePinLeft?e.hidePinLeft:n.hidePinLeft,n.hidePinRight=void 0===n.hidePinRight?e.hidePinRight:n.hidePinRight,n.pinnedLeft?(i.renderContainer="left",i.grid.createLeftContainer()):n.pinnedRight&&(i.renderContainer="right",i.grid.createRightContainer()),n.enablePinning){var t={name:"ui.grid.pinning.pinLeft",title:d.get().pinning.pinLeft,icon:"ui-grid-icon-left-open",shown:function(){return void 0===this.context.col.renderContainer||!this.context.col.renderContainer||"left"!==this.context.col.renderContainer},action:function(){a.pinColumn(this.context.col.grid,this.context.col,u.container.LEFT)}},r={name:"ui.grid.pinning.pinRight",title:d.get().pinning.pinRight,icon:"ui-grid-icon-right-open",shown:function(){return void 0===this.context.col.renderContainer||!this.context.col.renderContainer||"right"!==this.context.col.renderContainer},action:function(){a.pinColumn(this.context.col.grid,this.context.col,u.container.RIGHT)}},o={name:"ui.grid.pinning.unpin",title:d.get().pinning.unpin,icon:"ui-grid-icon-cancel",shown:function(){return void 0!==this.context.col.renderContainer&&null!==this.context.col.renderContainer&&"body"!==this.context.col.renderContainer},action:function(){a.pinColumn(this.context.col.grid,this.context.col,u.container.NONE)}};n.hidePinLeft||c.arrayContainsObjectWithProperty(i.menuItems,"name","ui.grid.pinning.pinLeft")||i.menuItems.push(t),n.hidePinRight||c.arrayContainsObjectWithProperty(i.menuItems,"name","ui.grid.pinning.pinRight")||i.menuItems.push(r),c.arrayContainsObjectWithProperty(i.menuItems,"name","ui.grid.pinning.unpin")||i.menuItems.push(o)}},pinColumn:function(n,i,e){e===u.container.NONE?(i.renderContainer=null,i.colDef.pinnedLeft=i.colDef.pinnedRight=!1):(i.renderContainer=e)===u.container.LEFT?n.createLeftContainer():e===u.container.RIGHT&&n.createRightContainer(),n.refresh().then(function(){n.api.pinning.raise.columnPinned(i.colDef,e)})}};return a}]),n.directive("uiGridPinning",["gridUtil","uiGridPinningService",function(n,r){return{require:"uiGrid",scope:!1,compile:function(){return{pre:function(n,i,e,t){r.initializeGrid(t.grid)},post:function(n,i,e,t){}}}}}])}();
\ No newline at end of file
diff --git a/release/4.4.11/ui-grid.resize-columns.js b/release/4.4.11/ui-grid.resize-columns.js
new file mode 100644
index 000000000..5b748b42b
--- /dev/null
+++ b/release/4.4.11/ui-grid.resize-columns.js
@@ -0,0 +1,569 @@
+/*!
+ * ui-grid - v4.4.11 - 2018-05-16
+ * Copyright (c) 2018 ; License: MIT
+ */
+
+(function(){
+ 'use strict';
+
+ /**
+ * @ngdoc overview
+ * @name ui.grid.resizeColumns
+ * @description
+ *
+ * # ui.grid.resizeColumns
+ *
+ *
Defaults to true
+ */
+ gridOptions.enableColumnResizing = gridOptions.enableColumnResizing !== false;
+
+ //legacy support
+ //use old name if it is explicitly false
+ if (gridOptions.enableColumnResize === false){
+ gridOptions.enableColumnResizing = false;
+ }
+ },
+
+ colResizerColumnBuilder: function (colDef, col, gridOptions) {
+
+ var promises = [];
+ /**
+ * @ngdoc object
+ * @name ui.grid.resizeColumns.api:ColumnDef
+ *
+ * @description ColumnDef for resizeColumns feature, these are available to be
+ * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
+ */
+
+ /**
+ * @ngdoc object
+ * @name enableColumnResizing
+ * @propertyOf ui.grid.resizeColumns.api:ColumnDef
+ * @description Enable column resizing on an individual column
+ *
Defaults to GridOptions.enableColumnResizing
+ */
+ //default to true unless gridOptions or colDef is explicitly false
+ colDef.enableColumnResizing = colDef.enableColumnResizing === undefined ? gridOptions.enableColumnResizing : colDef.enableColumnResizing;
+
+
+ //legacy support of old option name
+ if (colDef.enableColumnResize === false){
+ colDef.enableColumnResizing = false;
+ }
+
+ return $q.all(promises);
+ },
+
+ registerPublicApi: function (grid) {
+ /**
+ * @ngdoc object
+ * @name ui.grid.resizeColumns.api:PublicApi
+ * @description Public Api for column resize feature.
+ */
+ var publicApi = {
+ events: {
+ /**
+ * @ngdoc event
+ * @name columnSizeChanged
+ * @eventOf ui.grid.resizeColumns.api:PublicApi
+ * @description raised when column is resized
+ *
+ * gridApi.colResizable.on.columnSizeChanged(scope,function(colDef, deltaChange){})
+ *
+ * @param {object} colDef the column that was resized
+ * @param {integer} delta of the column size change
+ */
+ colResizable: {
+ columnSizeChanged: function (colDef, deltaChange) {
+ }
+ }
+ }
+ };
+ grid.api.registerEventsFromObject(publicApi.events);
+ },
+
+ fireColumnSizeChanged: function (grid, colDef, deltaChange) {
+ $rootScope.$applyAsync(function () {
+ if ( grid.api.colResizable ){
+ grid.api.colResizable.raise.columnSizeChanged(colDef, deltaChange);
+ } else {
+ gridUtil.logError("The resizeable api is not registered, this may indicate that you've included the module but not added the 'ui-grid-resize-columns' directive to your grid definition. Cannot raise any events.");
+ }
+ });
+ },
+
+ // get either this column, or the column next to this column, to resize,
+ // returns the column we're going to resize
+ findTargetCol: function(col, position, rtlMultiplier){
+ var renderContainer = col.getRenderContainer();
+
+ if (position === 'left') {
+ // Get the column to the left of this one
+ var colIndex = renderContainer.visibleColumnCache.indexOf(col);
+ return renderContainer.visibleColumnCache[colIndex - 1 * rtlMultiplier];
+ } else {
+ return col;
+ }
+ }
+
+ };
+
+ return service;
+
+ }]);
+
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.resizeColumns.directive:uiGridResizeColumns
+ * @element div
+ * @restrict A
+ * @description
+ * Enables resizing for all columns on the grid. If, for some reason, you want to use the ui-grid-resize-columns directive, but not allow column resizing, you can explicitly set the
+ * option to false. This prevents resizing for the entire grid, regardless of individual columnDef options.
+ *
+ * @example
+
+ * This feature depends on usage of the ui-grid-edit feature, and also benefits
+ * from use of ui-grid-cellNav to provide the full spreadsheet-like editing
+ * experience
+ *
+ */
+
+ var module = angular.module('ui.grid.rowEdit', ['ui.grid', 'ui.grid.edit', 'ui.grid.cellNav']);
+
+ /**
+ * @ngdoc object
+ * @name ui.grid.rowEdit.constant:uiGridRowEditConstants
+ *
+ * @description constants available in row edit module
+ */
+ module.constant('uiGridRowEditConstants', {
+ });
+
+ /**
+ * @ngdoc service
+ * @name ui.grid.rowEdit.service:uiGridRowEditService
+ *
+ * @description Services for row editing features
+ */
+ module.service('uiGridRowEditService', ['$interval', '$q', 'uiGridConstants', 'uiGridRowEditConstants', 'gridUtil',
+ function ($interval, $q, uiGridConstants, uiGridRowEditConstants, gridUtil) {
+
+ var service = {
+
+ initializeGrid: function (scope, grid) {
+ /**
+ * @ngdoc object
+ * @name ui.grid.rowEdit.api:PublicApi
+ *
+ * @description Public Api for rowEdit feature
+ */
+
+ grid.rowEdit = {};
+
+ var publicApi = {
+ events: {
+ rowEdit: {
+ /**
+ * @ngdoc event
+ * @eventOf ui.grid.rowEdit.api:PublicApi
+ * @name saveRow
+ * @description raised when a row is ready for saving. Once your
+ * row has saved you may need to use angular.extend to update the
+ * data entity with any changed data from your save (for example,
+ * lock version information if you're using optimistic locking,
+ * or last update time/user information).
+ *
+ * Your method should call setSavePromise somewhere in the body before
+ * returning control. The feature will then wait, with the gridRow greyed out
+ * whilst this promise is being resolved.
+ *
+ *
+ * gridApi.rowEdit.on.saveRow(scope,function(rowEntity){})
+ *
+ * and somewhere within the event handler:
+ *
+ * gridApi.rowEdit.setSavePromise( rowEntity, savePromise)
+ *
+ * @param {object} rowEntity the options.data element that was edited
+ * @returns {promise} Your saveRow method should return a promise, the
+ * promise should either be resolved (implying successful save), or
+ * rejected (implying an error).
+ */
+ saveRow: function (rowEntity) {
+ }
+ }
+ },
+ methods: {
+ rowEdit: {
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.rowEdit.api:PublicApi
+ * @name setSavePromise
+ * @description Sets the promise associated with the row save, mandatory that
+ * the saveRow event handler calls this method somewhere before returning.
+ *
+ * gridApi.rowEdit.setSavePromise(rowEntity, savePromise)
+ *
+ * @param {object} rowEntity a data row from the grid for which a save has
+ * been initiated
+ * @param {promise} savePromise the promise that will be resolved when the
+ * save is successful, or rejected if the save fails
+ *
+ */
+ setSavePromise: function ( rowEntity, savePromise) {
+ service.setSavePromise(grid, rowEntity, savePromise);
+ },
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.rowEdit.api:PublicApi
+ * @name getDirtyRows
+ * @description Returns all currently dirty rows
+ *
+ * gridApi.rowEdit.getDirtyRows(grid)
+ *
+ * @returns {array} An array of gridRows that are currently dirty
+ *
+ */
+ getDirtyRows: function () {
+ return grid.rowEdit.dirtyRows ? grid.rowEdit.dirtyRows : [];
+ },
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.rowEdit.api:PublicApi
+ * @name getErrorRows
+ * @description Returns all currently errored rows
+ *
+ * gridApi.rowEdit.getErrorRows(grid)
+ *
+ * @returns {array} An array of gridRows that are currently in error
+ *
+ */
+ getErrorRows: function () {
+ return grid.rowEdit.errorRows ? grid.rowEdit.errorRows : [];
+ },
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.rowEdit.api:PublicApi
+ * @name flushDirtyRows
+ * @description Triggers a save event for all currently dirty rows, could
+ * be used where user presses a save button or navigates away from the page
+ *
+ * gridApi.rowEdit.flushDirtyRows(grid)
+ *
+ * @returns {promise} a promise that represents the aggregate of all
+ * of the individual save promises - i.e. it will be resolved when all
+ * the individual save promises have been resolved.
+ *
+ */
+ flushDirtyRows: function () {
+ return service.flushDirtyRows(grid);
+ },
+
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.rowEdit.api:PublicApi
+ * @name setRowsDirty
+ * @description Sets each of the rows passed in dataRows
+ * to be dirty. note that if you have only just inserted the
+ * rows into your data you will need to wait for a $digest cycle
+ * before the gridRows are present - so often you would wrap this
+ * call in a $interval or $timeout
+ *
+ * $interval( function() {
+ * gridApi.rowEdit.setRowsDirty(myDataRows);
+ * }, 0, 1);
+ *
+ * @param {array} dataRows the data entities for which the gridRows
+ * should be set dirty.
+ *
+ */
+ setRowsDirty: function ( dataRows) {
+ service.setRowsDirty(grid, dataRows);
+ },
+
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.rowEdit.api:PublicApi
+ * @name setRowsClean
+ * @description Sets each of the rows passed in dataRows
+ * to be clean, removing them from the dirty cache and the error cache,
+ * and clearing the error flag and the dirty flag
+ *
+ * var gridRows = $scope.gridApi.rowEdit.getDirtyRows();
+ * var dataRows = gridRows.map( function( gridRow ) { return gridRow.entity; });
+ * $scope.gridApi.rowEdit.setRowsClean( dataRows );
+ *
+ * @param {array} dataRows the data entities for which the gridRows
+ * should be set clean.
+ *
+ */
+ setRowsClean: function ( dataRows) {
+ service.setRowsClean(grid, dataRows);
+ }
+ }
+ }
+ };
+
+ grid.api.registerEventsFromObject(publicApi.events);
+ grid.api.registerMethodsFromObject(publicApi.methods);
+
+ grid.api.core.on.renderingComplete( scope, function ( gridApi ) {
+ grid.api.edit.on.afterCellEdit( scope, service.endEditCell );
+ grid.api.edit.on.beginCellEdit( scope, service.beginEditCell );
+ grid.api.edit.on.cancelCellEdit( scope, service.cancelEditCell );
+
+ if ( grid.api.cellNav ) {
+ grid.api.cellNav.on.navigate( scope, service.navigate );
+ }
+ });
+
+ },
+
+ defaultGridOptions: function (gridOptions) {
+
+ /**
+ * @ngdoc object
+ * @name ui.grid.rowEdit.api:GridOptions
+ *
+ * @description Options for configuring the rowEdit feature, these are available to be
+ * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
+ */
+
+ },
+
+
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
+ * @name saveRow
+ * @description Returns a function that saves the specified row from the grid,
+ * and returns a promise
+ * @param {object} grid the grid for which dirty rows should be flushed
+ * @param {GridRow} gridRow the row that should be saved
+ * @returns {function} the saveRow function returns a function. That function
+ * in turn, when called, returns a promise relating to the save callback
+ */
+ saveRow: function ( grid, gridRow ) {
+ var self = this;
+
+ return function() {
+ gridRow.isSaving = true;
+
+ if ( gridRow.rowEditSavePromise ){
+ // don't save the row again if it's already saving - that causes stale object exceptions
+ return gridRow.rowEditSavePromise;
+ }
+
+ var promise = grid.api.rowEdit.raise.saveRow( gridRow.entity );
+
+ if ( gridRow.rowEditSavePromise ){
+ gridRow.rowEditSavePromise.then( self.processSuccessPromise( grid, gridRow ), self.processErrorPromise( grid, gridRow ));
+ } else {
+ gridUtil.logError( 'A promise was not returned when saveRow event was raised, either nobody is listening to event, or event handler did not return a promise' );
+ }
+ return promise;
+ };
+ },
+
+
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
+ * @name setSavePromise
+ * @description Sets the promise associated with the row save, mandatory that
+ * the saveRow event handler calls this method somewhere before returning.
+ *
+ * gridApi.rowEdit.setSavePromise(grid, rowEntity)
+ *
+ * @param {object} grid the grid for which dirty rows should be returned
+ * @param {object} rowEntity a data row from the grid for which a save has
+ * been initiated
+ * @param {promise} savePromise the promise that will be resolved when the
+ * save is successful, or rejected if the save fails
+ *
+ */
+ setSavePromise: function (grid, rowEntity, savePromise) {
+ var gridRow = grid.getRow( rowEntity );
+ gridRow.rowEditSavePromise = savePromise;
+ },
+
+
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
+ * @name processSuccessPromise
+ * @description Returns a function that processes the successful
+ * resolution of a save promise
+ * @param {object} grid the grid for which the promise should be processed
+ * @param {GridRow} gridRow the row that has been saved
+ * @returns {function} the success handling function
+ */
+ processSuccessPromise: function ( grid, gridRow ) {
+ var self = this;
+
+ return function() {
+ delete gridRow.isSaving;
+ delete gridRow.isDirty;
+ delete gridRow.isError;
+ delete gridRow.rowEditSaveTimer;
+ delete gridRow.rowEditSavePromise;
+ self.removeRow( grid.rowEdit.errorRows, gridRow );
+ self.removeRow( grid.rowEdit.dirtyRows, gridRow );
+ };
+ },
+
+
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
+ * @name processErrorPromise
+ * @description Returns a function that processes the failed
+ * resolution of a save promise
+ * @param {object} grid the grid for which the promise should be processed
+ * @param {GridRow} gridRow the row that is now in error
+ * @returns {function} the error handling function
+ */
+ processErrorPromise: function ( grid, gridRow ) {
+ return function() {
+ delete gridRow.isSaving;
+ delete gridRow.rowEditSaveTimer;
+ delete gridRow.rowEditSavePromise;
+
+ gridRow.isError = true;
+
+ if (!grid.rowEdit.errorRows){
+ grid.rowEdit.errorRows = [];
+ }
+ if (!service.isRowPresent( grid.rowEdit.errorRows, gridRow ) ){
+ grid.rowEdit.errorRows.push( gridRow );
+ }
+ };
+ },
+
+
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
+ * @name removeRow
+ * @description Removes a row from a cache of rows - either
+ * grid.rowEdit.errorRows or grid.rowEdit.dirtyRows. If the row
+ * is not present silently does nothing.
+ * @param {array} rowArray the array from which to remove the row
+ * @param {GridRow} gridRow the row that should be removed
+ */
+ removeRow: function( rowArray, removeGridRow ){
+ if (typeof(rowArray) === 'undefined' || rowArray === null){
+ return;
+ }
+
+ rowArray.forEach( function( gridRow, index ){
+ if ( gridRow.uid === removeGridRow.uid ){
+ rowArray.splice( index, 1);
+ }
+ });
+ },
+
+
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
+ * @name isRowPresent
+ * @description Checks whether a row is already present
+ * in the given array
+ * @param {array} rowArray the array in which to look for the row
+ * @param {GridRow} gridRow the row that should be looked for
+ */
+ isRowPresent: function( rowArray, removeGridRow ){
+ var present = false;
+ rowArray.forEach( function( gridRow, index ){
+ if ( gridRow.uid === removeGridRow.uid ){
+ present = true;
+ }
+ });
+ return present;
+ },
+
+
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
+ * @name flushDirtyRows
+ * @description Triggers a save event for all currently dirty rows, could
+ * be used where user presses a save button or navigates away from the page
+ *
+ * gridApi.rowEdit.flushDirtyRows(grid)
+ *
+ * @param {object} grid the grid for which dirty rows should be flushed
+ * @returns {promise} a promise that represents the aggregate of all
+ * of the individual save promises - i.e. it will be resolved when all
+ * the individual save promises have been resolved.
+ *
+ */
+ flushDirtyRows: function(grid){
+ var promises = [];
+ grid.api.rowEdit.getDirtyRows().forEach( function( gridRow ){
+ service.cancelTimer( grid, gridRow );
+ service.saveRow( grid, gridRow )();
+ promises.push( gridRow.rowEditSavePromise );
+ });
+
+ return $q.all( promises );
+ },
+
+
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
+ * @name endEditCell
+ * @description Receives an afterCellEdit event from the edit function,
+ * and sets flags as appropriate. Only the rowEntity parameter
+ * is processed, although other params are available. Grid
+ * is automatically provided by the gridApi.
+ * @param {object} rowEntity the data entity for which the cell
+ * was edited
+ */
+ endEditCell: function( rowEntity, colDef, newValue, previousValue ){
+ var grid = this.grid;
+ var gridRow = grid.getRow( rowEntity );
+ if ( !gridRow ){ gridUtil.logError( 'Unable to find rowEntity in grid data, dirty flag cannot be set' ); return; }
+
+ if ( newValue !== previousValue || gridRow.isDirty ){
+ if ( !grid.rowEdit.dirtyRows ){
+ grid.rowEdit.dirtyRows = [];
+ }
+
+ if ( !gridRow.isDirty ){
+ gridRow.isDirty = true;
+ grid.rowEdit.dirtyRows.push( gridRow );
+ }
+
+ delete gridRow.isError;
+
+ service.considerSetTimer( grid, gridRow );
+ }
+ },
+
+
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
+ * @name beginEditCell
+ * @description Receives a beginCellEdit event from the edit function,
+ * and cancels any rowEditSaveTimers if present, as the user is still editing
+ * this row. Only the rowEntity parameter
+ * is processed, although other params are available. Grid
+ * is automatically provided by the gridApi.
+ * @param {object} rowEntity the data entity for which the cell
+ * editing has commenced
+ */
+ beginEditCell: function( rowEntity, colDef ){
+ var grid = this.grid;
+ var gridRow = grid.getRow( rowEntity );
+ if ( !gridRow ){ gridUtil.logError( 'Unable to find rowEntity in grid data, timer cannot be cancelled' ); return; }
+
+ service.cancelTimer( grid, gridRow );
+ },
+
+
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
+ * @name cancelEditCell
+ * @description Receives a cancelCellEdit event from the edit function,
+ * and if the row was already dirty, restarts the save timer. If the row
+ * was not already dirty, then it's not dirty now either and does nothing.
+ *
+ * Only the rowEntity parameter
+ * is processed, although other params are available. Grid
+ * is automatically provided by the gridApi.
+ *
+ * @param {object} rowEntity the data entity for which the cell
+ * editing was cancelled
+ */
+ cancelEditCell: function( rowEntity, colDef ){
+ var grid = this.grid;
+ var gridRow = grid.getRow( rowEntity );
+ if ( !gridRow ){ gridUtil.logError( 'Unable to find rowEntity in grid data, timer cannot be set' ); return; }
+
+ service.considerSetTimer( grid, gridRow );
+ },
+
+
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
+ * @name navigate
+ * @description cellNav tells us that the selected cell has changed. If
+ * the new row had a timer running, then stop it similar to in a beginCellEdit
+ * call. If the old row is dirty and not the same as the new row, then
+ * start a timer on it.
+ * @param {object} newRowCol the row and column that were selected
+ * @param {object} oldRowCol the row and column that was left
+ *
+ */
+ navigate: function( newRowCol, oldRowCol ){
+ var grid = this.grid;
+ if ( newRowCol.row.rowEditSaveTimer ){
+ service.cancelTimer( grid, newRowCol.row );
+ }
+
+ if ( oldRowCol && oldRowCol.row && oldRowCol.row !== newRowCol.row ){
+ service.considerSetTimer( grid, oldRowCol.row );
+ }
+ },
+
+
+ /**
+ * @ngdoc property
+ * @propertyOf ui.grid.rowEdit.api:GridOptions
+ * @name rowEditWaitInterval
+ * @description How long the grid should wait for another change on this row
+ * before triggering a save (in milliseconds). If set to -1, then saves are
+ * never triggered by timer (implying that the user will call flushDirtyRows()
+ * manually)
+ *
+ * @example
+ * Setting the wait interval to 4 seconds
+ *
+ * $scope.gridOptions = { rowEditWaitInterval: 4000 }
+ *
+ *
+ */
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
+ * @name considerSetTimer
+ * @description Consider setting a timer on this row (if it is dirty). if there is a timer running
+ * on the row and the row isn't currently saving, cancel it, using cancelTimer, then if the row is
+ * dirty and not currently saving then set a new timer
+ * @param {object} grid the grid for which we are processing
+ * @param {GridRow} gridRow the row for which the timer should be adjusted
+ *
+ */
+ considerSetTimer: function( grid, gridRow ){
+ service.cancelTimer( grid, gridRow );
+
+ if ( gridRow.isDirty && !gridRow.isSaving ){
+ if ( grid.options.rowEditWaitInterval !== -1 ){
+ var waitTime = grid.options.rowEditWaitInterval ? grid.options.rowEditWaitInterval : 2000;
+ gridRow.rowEditSaveTimer = $interval( service.saveRow( grid, gridRow ), waitTime, 1);
+ }
+ }
+ },
+
+
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
+ * @name cancelTimer
+ * @description cancel the $interval for any timer running on this row
+ * then delete the timer itself
+ * @param {object} grid the grid for which we are processing
+ * @param {GridRow} gridRow the row for which the timer should be adjusted
+ *
+ */
+ cancelTimer: function( grid, gridRow ){
+ if ( gridRow.rowEditSaveTimer && !gridRow.isSaving ){
+ $interval.cancel(gridRow.rowEditSaveTimer);
+ delete gridRow.rowEditSaveTimer;
+ }
+ },
+
+
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
+ * @name setRowsDirty
+ * @description Sets each of the rows passed in dataRows
+ * to be dirty. note that if you have only just inserted the
+ * rows into your data you will need to wait for a $digest cycle
+ * before the gridRows are present - so often you would wrap this
+ * call in a $interval or $timeout
+ *
+ * $interval( function() {
+ * gridApi.rowEdit.setRowsDirty( myDataRows);
+ * }, 0, 1);
+ *
+ * @param {object} grid the grid for which rows should be set dirty
+ * @param {array} dataRows the data entities for which the gridRows
+ * should be set dirty.
+ *
+ */
+ setRowsDirty: function( grid, myDataRows ) {
+ var gridRow;
+ myDataRows.forEach( function( value, index ){
+ gridRow = grid.getRow( value );
+ if ( gridRow ){
+ if ( !grid.rowEdit.dirtyRows ){
+ grid.rowEdit.dirtyRows = [];
+ }
+
+ if ( !gridRow.isDirty ){
+ gridRow.isDirty = true;
+ grid.rowEdit.dirtyRows.push( gridRow );
+ }
+
+ delete gridRow.isError;
+
+ service.considerSetTimer( grid, gridRow );
+ } else {
+ gridUtil.logError( "requested row not found in rowEdit.setRowsDirty, row was: " + value );
+ }
+ });
+ },
+
+
+ /**
+ * @ngdoc method
+ * @methodOf ui.grid.rowEdit.service:uiGridRowEditService
+ * @name setRowsClean
+ * @description Sets each of the rows passed in dataRows
+ * to be clean, clearing the dirty flag and the error flag, and removing
+ * the rows from the dirty and error caches.
+ * @param {object} grid the grid for which rows should be set clean
+ * @param {array} dataRows the data entities for which the gridRows
+ * should be set clean.
+ *
+ */
+ setRowsClean: function( grid, myDataRows ) {
+ var gridRow;
+
+ myDataRows.forEach( function( value, index ){
+ gridRow = grid.getRow( value );
+ if ( gridRow ){
+ delete gridRow.isDirty;
+ service.removeRow( grid.rowEdit.dirtyRows, gridRow );
+ service.cancelTimer( grid, gridRow );
+
+ delete gridRow.isError;
+ service.removeRow( grid.rowEdit.errorRows, gridRow );
+ } else {
+ gridUtil.logError( "requested row not found in rowEdit.setRowsClean, row was: " + value );
+ }
+ });
+ }
+
+ };
+
+ return service;
+
+ }]);
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.rowEdit.directive:uiGridEdit
+ * @element div
+ * @restrict A
+ *
+ * @description Adds row editing features to the ui-grid-edit directive.
+ *
+ */
+ module.directive('uiGridRowEdit', ['gridUtil', 'uiGridRowEditService', 'uiGridEditConstants',
+ function (gridUtil, uiGridRowEditService, uiGridEditConstants) {
+ return {
+ replace: true,
+ priority: 0,
+ require: '^uiGrid',
+ scope: false,
+ compile: function () {
+ return {
+ pre: function ($scope, $elm, $attrs, uiGridCtrl) {
+ uiGridRowEditService.initializeGrid($scope, uiGridCtrl.grid);
+ },
+ post: function ($scope, $elm, $attrs, uiGridCtrl) {
+ }
+ };
+ }
+ };
+ }]);
+
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.rowEdit.directive:uiGridViewport
+ * @element div
+ *
+ * @description Stacks on top of ui.grid.uiGridViewport to alter the attributes used
+ * for the grid row to allow coloring of saving and error rows
+ */
+ module.directive('uiGridViewport',
+ ['$compile', 'uiGridConstants', 'gridUtil', '$parse',
+ function ($compile, uiGridConstants, gridUtil, $parse) {
+ return {
+ priority: -200, // run after default directive
+ scope: false,
+ compile: function ($elm, $attrs) {
+ var rowRepeatDiv = angular.element($elm.children().children()[0]);
+
+ var existingNgClass = rowRepeatDiv.attr("ng-class");
+ var newNgClass = '';
+ if ( existingNgClass ) {
+ newNgClass = existingNgClass.slice(0, -1) + ", 'ui-grid-row-dirty': row.isDirty, 'ui-grid-row-saving': row.isSaving, 'ui-grid-row-error': row.isError}";
+ } else {
+ newNgClass = "{'ui-grid-row-dirty': row.isDirty, 'ui-grid-row-saving': row.isSaving, 'ui-grid-row-error': row.isError}";
+ }
+ rowRepeatDiv.attr("ng-class", newNgClass);
+
+ return {
+ pre: function ($scope, $elm, $attrs, controllers) {
+
+ },
+ post: function ($scope, $elm, $attrs, controllers) {
+ }
+ };
+ }
+ };
+ }]);
+
+})();
diff --git a/release/4.4.11/ui-grid.row-edit.min.js b/release/4.4.11/ui-grid.row-edit.min.js
new file mode 100644
index 000000000..27a9ef4f6
--- /dev/null
+++ b/release/4.4.11/ui-grid.row-edit.min.js
@@ -0,0 +1,7 @@
+/*!
+ * ui-grid - v4.4.11 - 2018-05-16
+ * Copyright (c) 2018 ; License: MIT
+ */
+
+
+!function(){"use strict";var r=angular.module("ui.grid.rowEdit",["ui.grid","ui.grid.edit","ui.grid.cellNav"]);r.constant("uiGridRowEditConstants",{}),r.service("uiGridRowEditService",["$interval","$q","uiGridConstants","uiGridRowEditConstants","gridUtil",function(t,r,i,e,s){var d={initializeGrid:function(i,e){e.rowEdit={};var r={events:{rowEdit:{saveRow:function(r){}}},methods:{rowEdit:{setSavePromise:function(r,i){d.setSavePromise(e,r,i)},getDirtyRows:function(){return e.rowEdit.dirtyRows?e.rowEdit.dirtyRows:[]},getErrorRows:function(){return e.rowEdit.errorRows?e.rowEdit.errorRows:[]},flushDirtyRows:function(){return d.flushDirtyRows(e)},setRowsDirty:function(r){d.setRowsDirty(e,r)},setRowsClean:function(r){d.setRowsClean(e,r)}}}};e.api.registerEventsFromObject(r.events),e.api.registerMethodsFromObject(r.methods),e.api.core.on.renderingComplete(i,function(r){e.api.edit.on.afterCellEdit(i,d.endEditCell),e.api.edit.on.beginCellEdit(i,d.beginEditCell),e.api.edit.on.cancelCellEdit(i,d.cancelEditCell),e.api.cellNav&&e.api.cellNav.on.navigate(i,d.navigate)})},defaultGridOptions:function(r){},saveRow:function(i,e){var t=this;return function(){if(e.isSaving=!0,e.rowEditSavePromise)return e.rowEditSavePromise;var r=i.api.rowEdit.raise.saveRow(e.entity);return e.rowEditSavePromise?e.rowEditSavePromise.then(t.processSuccessPromise(i,e),t.processErrorPromise(i,e)):s.logError("A promise was not returned when saveRow event was raised, either nobody is listening to event, or event handler did not return a promise"),r}},setSavePromise:function(r,i,e){r.getRow(i).rowEditSavePromise=e},processSuccessPromise:function(r,i){var e=this;return function(){delete i.isSaving,delete i.isDirty,delete i.isError,delete i.rowEditSaveTimer,delete i.rowEditSavePromise,e.removeRow(r.rowEdit.errorRows,i),e.removeRow(r.rowEdit.dirtyRows,i)}},processErrorPromise:function(r,i){return function(){delete i.isSaving,delete i.rowEditSaveTimer,delete i.rowEditSavePromise,i.isError=!0,r.rowEdit.errorRows||(r.rowEdit.errorRows=[]),d.isRowPresent(r.rowEdit.errorRows,i)||r.rowEdit.errorRows.push(i)}},removeRow:function(e,t){null!=e&&e.forEach(function(r,i){r.uid===t.uid&&e.splice(i,1)})},isRowPresent:function(r,e){var t=!1;return r.forEach(function(r,i){r.uid===e.uid&&(t=!0)}),t},flushDirtyRows:function(i){var e=[];return i.api.rowEdit.getDirtyRows().forEach(function(r){d.cancelTimer(i,r),d.saveRow(i,r)(),e.push(r.rowEditSavePromise)}),r.all(e)},endEditCell:function(r,i,e,t){var o=this.grid,n=o.getRow(r);n?(e!==t||n.isDirty)&&(o.rowEdit.dirtyRows||(o.rowEdit.dirtyRows=[]),n.isDirty||(n.isDirty=!0,o.rowEdit.dirtyRows.push(n)),delete n.isError,d.considerSetTimer(o,n)):s.logError("Unable to find rowEntity in grid data, dirty flag cannot be set")},beginEditCell:function(r,i){var e=this.grid,t=e.getRow(r);t?d.cancelTimer(e,t):s.logError("Unable to find rowEntity in grid data, timer cannot be cancelled")},cancelEditCell:function(r,i){var e=this.grid,t=e.getRow(r);t?d.considerSetTimer(e,t):s.logError("Unable to find rowEntity in grid data, timer cannot be set")},navigate:function(r,i){var e=this.grid;r.row.rowEditSaveTimer&&d.cancelTimer(e,r.row),i&&i.row&&i.row!==r.row&&d.considerSetTimer(e,i.row)},considerSetTimer:function(r,i){if(d.cancelTimer(r,i),i.isDirty&&!i.isSaving&&-1!==r.options.rowEditWaitInterval){var e=r.options.rowEditWaitInterval?r.options.rowEditWaitInterval:2e3;i.rowEditSaveTimer=t(d.saveRow(r,i),e,1)}},cancelTimer:function(r,i){i.rowEditSaveTimer&&!i.isSaving&&(t.cancel(i.rowEditSaveTimer),delete i.rowEditSaveTimer)},setRowsDirty:function(e,r){var t;r.forEach(function(r,i){(t=e.getRow(r))?(e.rowEdit.dirtyRows||(e.rowEdit.dirtyRows=[]),t.isDirty||(t.isDirty=!0,e.rowEdit.dirtyRows.push(t)),delete t.isError,d.considerSetTimer(e,t)):s.logError("requested row not found in rowEdit.setRowsDirty, row was: "+r)})},setRowsClean:function(e,r){var t;r.forEach(function(r,i){(t=e.getRow(r))?(delete t.isDirty,d.removeRow(e.rowEdit.dirtyRows,t),d.cancelTimer(e,t),delete t.isError,d.removeRow(e.rowEdit.errorRows,t)):s.logError("requested row not found in rowEdit.setRowsClean, row was: "+r)})}};return d}]),r.directive("uiGridRowEdit",["gridUtil","uiGridRowEditService","uiGridEditConstants",function(r,o,i){return{replace:!0,priority:0,require:"^uiGrid",scope:!1,compile:function(){return{pre:function(r,i,e,t){o.initializeGrid(r,t.grid)},post:function(r,i,e,t){}}}}}]),r.directive("uiGridViewport",["$compile","uiGridConstants","gridUtil","$parse",function(r,i,e,t){return{priority:-200,scope:!1,compile:function(r,i){var e=angular.element(r.children().children()[0]),t=e.attr("ng-class"),o="";return o=t?t.slice(0,-1)+", 'ui-grid-row-dirty': row.isDirty, 'ui-grid-row-saving': row.isSaving, 'ui-grid-row-error': row.isError}":"{'ui-grid-row-dirty': row.isDirty, 'ui-grid-row-saving': row.isSaving, 'ui-grid-row-error': row.isError}",e.attr("ng-class",o),{pre:function(r,i,e,t){},post:function(r,i,e,t){}}}}}])}();
\ No newline at end of file
diff --git a/release/4.4.11/ui-grid.saveState.js b/release/4.4.11/ui-grid.saveState.js
new file mode 100644
index 000000000..1c0d05bea
--- /dev/null
+++ b/release/4.4.11/ui-grid.saveState.js
@@ -0,0 +1,836 @@
+/*!
+ * ui-grid - v4.4.11 - 2018-05-16
+ * Copyright (c) 2018 ; License: MIT
+ */
+
+(function () {
+ 'use strict';
+
+ /**
+ * @ngdoc overview
+ * @name ui.grid.saveState
+ * @description
+ *
+ * # ui.grid.saveState
+ *
+ *
+ *
+ *
+ *
+ */
+
+ var module = angular.module('ui.grid.saveState', ['ui.grid', 'ui.grid.selection', 'ui.grid.cellNav', 'ui.grid.grouping', 'ui.grid.pinning', 'ui.grid.treeView']);
+
+ /**
+ * @ngdoc object
+ * @name ui.grid.saveState.constant:uiGridSaveStateConstants
+ *
+ * @description constants available in save state module
+ */
+
+ module.constant('uiGridSaveStateConstants', {
+ featureName: 'saveState'
+ });
+
+ /**
+ * @ngdoc service
+ * @name ui.grid.saveState.service:uiGridSaveStateService
+ *
+ * @description Services for saveState feature
+ */
+ module.service('uiGridSaveStateService', ['$q', 'uiGridSaveStateConstants', 'gridUtil', '$compile', '$interval', 'uiGridConstants',
+ function ($q, uiGridSaveStateConstants, gridUtil, $compile, $interval, uiGridConstants ) {
+
+ var service = {
+
+ initializeGrid: function (grid) {
+
+ //add feature namespace and any properties to grid for needed state
+ grid.saveState = {};
+ this.defaultGridOptions(grid.options);
+
+ /**
+ * @ngdoc object
+ * @name ui.grid.saveState.api:PublicApi
+ *
+ * @description Public Api for saveState feature
+ */
+ var publicApi = {
+ events: {
+ saveState: {
+ }
+ },
+ methods: {
+ saveState: {
+ /**
+ * @ngdoc function
+ * @name save
+ * @methodOf ui.grid.saveState.api:PublicApi
+ * @description Packages the current state of the grid into
+ * an object, and provides it to the user for saving
+ * @returns {object} the state as a javascript object that can be saved
+ */
+ save: function () {
+ return service.save(grid);
+ },
+ /**
+ * @ngdoc function
+ * @name restore
+ * @methodOf ui.grid.saveState.api:PublicApi
+ * @description Restores the provided state into the grid
+ * @param {scope} $scope a scope that we can broadcast on
+ * @param {object} state the state that should be restored into the grid
+ * @returns {object} the promise created by refresh
+ */
+ restore: function ( $scope, state) {
+ return service.restore(grid, $scope, state);
+ }
+ }
+ }
+ };
+
+ grid.api.registerEventsFromObject(publicApi.events);
+
+ grid.api.registerMethodsFromObject(publicApi.methods);
+
+ },
+
+ defaultGridOptions: function (gridOptions) {
+ //default option to true unless it was explicitly set to false
+ /**
+ * @ngdoc object
+ * @name ui.grid.saveState.api:GridOptions
+ *
+ * @description GridOptions for saveState feature, these are available to be
+ * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
+ */
+ /**
+ * @ngdoc object
+ * @name saveWidths
+ * @propertyOf ui.grid.saveState.api:GridOptions
+ * @description Save the current column widths. Note that unless
+ * you've provided the user with some way to resize their columns (say
+ * the resize columns feature), then this makes little sense.
+ *
Defaults to true
+ */
+ gridOptions.saveWidths = gridOptions.saveWidths !== false;
+ /**
+ * @ngdoc object
+ * @name saveOrder
+ * @propertyOf ui.grid.saveState.api:GridOptions
+ * @description Restore the current column order. Note that unless
+ * you've provided the user with some way to reorder their columns (for
+ * example the move columns feature), this makes little sense.
+ *
Defaults to true
+ */
+ gridOptions.saveOrder = gridOptions.saveOrder !== false;
+ /**
+ * @ngdoc object
+ * @name saveScroll
+ * @propertyOf ui.grid.saveState.api:GridOptions
+ * @description Save the current scroll position. Note that this
+ * is saved as the percentage of the grid scrolled - so if your
+ * user returns to a grid with a significantly different number of
+ * rows (perhaps some data has been deleted) then the scroll won't
+ * actually show the same rows as before. If you want to scroll to
+ * a specific row then you should instead use the saveFocus option, which
+ * is the default.
+ *
+ * Note that this element will only be saved if the cellNav feature is
+ * enabled
+ *
Defaults to false
+ */
+ gridOptions.saveScroll = gridOptions.saveScroll === true;
+ /**
+ * @ngdoc object
+ * @name saveFocus
+ * @propertyOf ui.grid.saveState.api:GridOptions
+ * @description Save the current focused cell. On returning
+ * to this focused cell we'll also scroll. This option is
+ * preferred to the saveScroll option, so is set to true by
+ * default. If saveScroll is set to true then this option will
+ * be disabled.
+ *
+ * By default this option saves the current row number and column
+ * number, and returns to that row and column. However, if you define
+ * a saveRowIdentity function, then it will return you to the currently
+ * selected column within that row (in a business sense - so if some
+ * rows have been deleted, it will still find the same data, presuming it
+ * still exists in the list. If it isn't in the list then it will instead
+ * return to the same row number - i.e. scroll percentage)
+ *
+ * Note that this option will do nothing if the cellNav
+ * feature is not enabled.
+ *
+ *
Defaults to true (unless saveScroll is true)
+ */
+ gridOptions.saveFocus = gridOptions.saveScroll !== true && gridOptions.saveFocus !== false;
+ /**
+ * @ngdoc object
+ * @name saveRowIdentity
+ * @propertyOf ui.grid.saveState.api:GridOptions
+ * @description A function that can be called, passing in a rowEntity,
+ * and that will return a unique id for that row. This might simply
+ * return the `id` field from that row (if you have one), or it might
+ * concatenate some fields within the row to make a unique value.
+ *
+ * This value will be used to find the same row again and set the focus
+ * to it, if it exists when we return.
+ *
+ *
Defaults to undefined
+ */
+ /**
+ * @ngdoc object
+ * @name saveVisible
+ * @propertyOf ui.grid.saveState.api:GridOptions
+ * @description Save whether or not columns are visible.
+ *
+ *
Defaults to true
+ */
+ gridOptions.saveVisible = gridOptions.saveVisible !== false;
+ /**
+ * @ngdoc object
+ * @name saveSort
+ * @propertyOf ui.grid.saveState.api:GridOptions
+ * @description Save the current sort state for each column
+ *
+ *
Defaults to true
+ */
+ gridOptions.saveSort = gridOptions.saveSort !== false;
+ /**
+ * @ngdoc object
+ * @name saveFilter
+ * @propertyOf ui.grid.saveState.api:GridOptions
+ * @description Save the current filter state for each column
+ *
+ *
Defaults to true
+ */
+ gridOptions.saveFilter = gridOptions.saveFilter !== false;
+ /**
+ * @ngdoc object
+ * @name saveSelection
+ * @propertyOf ui.grid.saveState.api:GridOptions
+ * @description Save the currently selected rows. If the `saveRowIdentity` callback
+ * is defined, then it will save the id of the row and select that. If not, then
+ * it will attempt to select the rows by row number, which will give the wrong results
+ * if the data set has changed in the mean-time.
+ *
+ * Note that this option only does anything
+ * if the selection feature is enabled.
+ *
+ *
Defaults to true
+ */
+ gridOptions.saveSelection = gridOptions.saveSelection !== false;
+ /**
+ * @ngdoc object
+ * @name saveGrouping
+ * @propertyOf ui.grid.saveState.api:GridOptions
+ * @description Save the grouping configuration. If set to true and the
+ * grouping feature is not enabled then does nothing.
+ *
+ *
Defaults to true
+ */
+ gridOptions.saveGrouping = gridOptions.saveGrouping !== false;
+ /**
+ * @ngdoc object
+ * @name saveGroupingExpandedStates
+ * @propertyOf ui.grid.saveState.api:GridOptions
+ * @description Save the grouping row expanded states. If set to true and the
+ * grouping feature is not enabled then does nothing.
+ *
+ * This can be quite a bit of data, in many cases you wouldn't want to save this
+ * information.
+ *
+ *
Defaults to false
+ */
+ gridOptions.saveGroupingExpandedStates = gridOptions.saveGroupingExpandedStates === true;
+ /**
+ * @ngdoc object
+ * @name savePinning
+ * @propertyOf ui.grid.saveState.api:GridOptions
+ * @description Save pinning state for columns.
+ *
+ *
Defaults to true
+ */
+ gridOptions.savePinning = gridOptions.savePinning !== false;
+ /**
+ * @ngdoc object
+ * @name saveTreeView
+ * @propertyOf ui.grid.saveState.api:GridOptions
+ * @description Save the treeView configuration. If set to true and the
+ * treeView feature is not enabled then does nothing.
+ *
+ *
Defaults to true
+ */
+ gridOptions.saveTreeView = gridOptions.saveTreeView !== false;
+ },
+
+
+
+ /**
+ * @ngdoc function
+ * @name save
+ * @methodOf ui.grid.saveState.service:uiGridSaveStateService
+ * @description Saves the current grid state into an object, and
+ * passes that object back to the caller
+ * @param {Grid} grid the grid whose state we'd like to save
+ * @returns {object} the state ready to be saved
+ */
+ save: function (grid) {
+ var savedState = {};
+
+ savedState.columns = service.saveColumns( grid );
+ savedState.scrollFocus = service.saveScrollFocus( grid );
+ savedState.selection = service.saveSelection( grid );
+ savedState.grouping = service.saveGrouping( grid );
+ savedState.treeView = service.saveTreeView( grid );
+ savedState.pagination = service.savePagination( grid );
+
+ return savedState;
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name restore
+ * @methodOf ui.grid.saveState.service:uiGridSaveStateService
+ * @description Applies the provided state to the grid
+ *
+ * @param {Grid} grid the grid whose state we'd like to restore
+ * @param {scope} $scope a scope that we can broadcast on
+ * @param {object} state the state we'd like to restore
+ * @returns {object} the promise created by refresh
+ */
+ restore: function( grid, $scope, state ){
+ if ( state.columns ) {
+ service.restoreColumns( grid, state.columns );
+ }
+
+ if ( state.scrollFocus ){
+ service.restoreScrollFocus( grid, $scope, state.scrollFocus );
+ }
+
+ if ( state.selection ){
+ service.restoreSelection( grid, state.selection );
+ }
+
+ if ( state.grouping ){
+ service.restoreGrouping( grid, state.grouping );
+ }
+
+ if ( state.treeView ){
+ service.restoreTreeView( grid, state.treeView );
+ }
+
+ if ( state.pagination ){
+ service.restorePagination( grid, state.pagination );
+ }
+
+ return grid.refresh();
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name saveColumns
+ * @methodOf ui.grid.saveState.service:uiGridSaveStateService
+ * @description Saves the column setup, including sort, filters, ordering,
+ * pinning and column widths.
+ *
+ * Works through the current columns, storing them in order. Stores the
+ * column name, then the visible flag, width, sort and filters for each column.
+ *
+ * @param {Grid} grid the grid whose state we'd like to save
+ * @returns {array} the columns state ready to be saved
+ */
+ saveColumns: function( grid ) {
+ var columns = [];
+ grid.getOnlyDataColumns().forEach( function( column ) {
+ var savedColumn = {};
+ savedColumn.name = column.name;
+
+ if ( grid.options.saveVisible ){
+ savedColumn.visible = column.visible;
+ }
+
+ if ( grid.options.saveWidths ){
+ savedColumn.width = column.width;
+ }
+
+ // these two must be copied, not just pointed too - otherwise our saved state is pointing to the same object as current state
+ if ( grid.options.saveSort ){
+ savedColumn.sort = angular.copy( column.sort );
+ }
+
+ if ( grid.options.saveFilter ){
+ savedColumn.filters = [];
+ column.filters.forEach( function( filter ){
+ var copiedFilter = {};
+ angular.forEach( filter, function( value, key) {
+ if ( key !== 'condition' && key !== '$$hashKey' && key !== 'placeholder'){
+ copiedFilter[key] = value;
+ }
+ });
+ savedColumn.filters.push(copiedFilter);
+ });
+ }
+
+ if ( !!grid.api.pinning && grid.options.savePinning ){
+ savedColumn.pinned = column.renderContainer ? column.renderContainer : '';
+ }
+
+ columns.push( savedColumn );
+ });
+
+ return columns;
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name saveScrollFocus
+ * @methodOf ui.grid.saveState.service:uiGridSaveStateService
+ * @description Saves the currently scroll or focus.
+ *
+ * If cellNav isn't present then does nothing - we can't return
+ * to the scroll position without cellNav anyway.
+ *
+ * If the cellNav module is present, and saveFocus is true, then
+ * it saves the currently focused cell. If rowIdentity is present
+ * then saves using rowIdentity, otherwise saves visibleRowNum.
+ *
+ * If the cellNav module is not present, and saveScroll is true, then
+ * it approximates the current scroll row and column, and saves that.
+ *
+ * @param {Grid} grid the grid whose state we'd like to save
+ * @returns {object} the selection state ready to be saved
+ */
+ saveScrollFocus: function( grid ){
+ if ( !grid.api.cellNav ){
+ return {};
+ }
+
+ var scrollFocus = {};
+ if ( grid.options.saveFocus ){
+ scrollFocus.focus = true;
+ var rowCol = grid.api.cellNav.getFocusedCell();
+ if ( rowCol !== null ) {
+ if ( rowCol.col !== null ){
+ scrollFocus.colName = rowCol.col.colDef.name;
+ }
+ if ( rowCol.row !== null ){
+ scrollFocus.rowVal = service.getRowVal( grid, rowCol.row );
+ }
+ }
+ }
+
+ if ( grid.options.saveScroll || grid.options.saveFocus && !scrollFocus.colName && !scrollFocus.rowVal ) {
+ scrollFocus.focus = false;
+ if ( grid.renderContainers.body.prevRowScrollIndex ){
+ scrollFocus.rowVal = service.getRowVal( grid, grid.renderContainers.body.visibleRowCache[ grid.renderContainers.body.prevRowScrollIndex ]);
+ }
+
+ if ( grid.renderContainers.body.prevColScrollIndex ){
+ scrollFocus.colName = grid.renderContainers.body.visibleColumnCache[ grid.renderContainers.body.prevColScrollIndex ].name;
+ }
+ }
+
+ return scrollFocus;
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name saveSelection
+ * @methodOf ui.grid.saveState.service:uiGridSaveStateService
+ * @description Saves the currently selected rows, if the selection feature is enabled
+ * @param {Grid} grid the grid whose state we'd like to save
+ * @returns {array} the selection state ready to be saved
+ */
+ saveSelection: function( grid ){
+ if ( !grid.api.selection || !grid.options.saveSelection ){
+ return [];
+ }
+
+ var selection = grid.api.selection.getSelectedGridRows().map( function( gridRow ) {
+ return service.getRowVal( grid, gridRow );
+ });
+
+ return selection;
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name saveGrouping
+ * @methodOf ui.grid.saveState.service:uiGridSaveStateService
+ * @description Saves the grouping state, if the grouping feature is enabled
+ * @param {Grid} grid the grid whose state we'd like to save
+ * @returns {object} the grouping state ready to be saved
+ */
+ saveGrouping: function( grid ){
+ if ( !grid.api.grouping || !grid.options.saveGrouping ){
+ return {};
+ }
+
+ return grid.api.grouping.getGrouping( grid.options.saveGroupingExpandedStates );
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name savePagination
+ * @methodOf ui.grid.saveState.service:uiGridSaveStateService
+ * @description Saves the pagination state, if the pagination feature is enabled
+ * @param {Grid} grid the grid whose state we'd like to save
+ * @returns {object} the pagination state ready to be saved
+ */
+ savePagination: function( grid ) {
+ if ( !grid.api.pagination || !grid.options.paginationPageSize ){
+ return {};
+ }
+
+ return {
+ paginationCurrentPage: grid.options.paginationCurrentPage,
+ paginationPageSize: grid.options.paginationPageSize
+ };
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name saveTreeView
+ * @methodOf ui.grid.saveState.service:uiGridSaveStateService
+ * @description Saves the tree view state, if the tree feature is enabled
+ * @param {Grid} grid the grid whose state we'd like to save
+ * @returns {object} the tree view state ready to be saved
+ */
+ saveTreeView: function( grid ){
+ if ( !grid.api.treeView || !grid.options.saveTreeView ){
+ return {};
+ }
+
+ return grid.api.treeView.getTreeView();
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name getRowVal
+ * @methodOf ui.grid.saveState.service:uiGridSaveStateService
+ * @description Helper function that gets either the rowNum or
+ * the saveRowIdentity, given a gridRow
+ * @param {Grid} grid the grid the row is in
+ * @param {GridRow} gridRow the row we want the rowNum for
+ * @returns {object} an object containing { identity: true/false, row: rowNumber/rowIdentity }
+ *
+ */
+ getRowVal: function( grid, gridRow ){
+ if ( !gridRow ) {
+ return null;
+ }
+
+ var rowVal = {};
+ if ( grid.options.saveRowIdentity ){
+ rowVal.identity = true;
+ rowVal.row = grid.options.saveRowIdentity( gridRow.entity );
+ } else {
+ rowVal.identity = false;
+ rowVal.row = grid.renderContainers.body.visibleRowCache.indexOf( gridRow );
+ }
+ return rowVal;
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name restoreColumns
+ * @methodOf ui.grid.saveState.service:uiGridSaveStateService
+ * @description Restores the columns, including order, visible, width,
+ * pinning, sort and filters.
+ *
+ * @param {Grid} grid the grid whose state we'd like to restore
+ * @param {object} columnsState the list of columns we had before, with their state
+ */
+ restoreColumns: function( grid, columnsState ){
+ var isSortChanged = false;
+
+ columnsState.forEach( function( columnState, index ) {
+ var currentCol = grid.getColumn( columnState.name );
+
+ if ( currentCol && !grid.isRowHeaderColumn(currentCol) ){
+ if ( grid.options.saveVisible &&
+ ( currentCol.visible !== columnState.visible ||
+ currentCol.colDef.visible !== columnState.visible ) ){
+ currentCol.visible = columnState.visible;
+ currentCol.colDef.visible = columnState.visible;
+ grid.api.core.raise.columnVisibilityChanged(currentCol);
+ }
+
+ if ( grid.options.saveWidths && currentCol.width !== columnState.width){
+ currentCol.width = columnState.width;
+ currentCol.hasCustomWidth = true;
+ }
+
+ if ( grid.options.saveSort &&
+ !angular.equals(currentCol.sort, columnState.sort) &&
+ !( currentCol.sort === undefined && angular.isEmpty(columnState.sort) ) ){
+ currentCol.sort = angular.copy( columnState.sort );
+ isSortChanged = true;
+ }
+
+ if ( grid.options.saveFilter &&
+ !angular.equals(currentCol.filters, columnState.filters ) ){
+ columnState.filters.forEach( function( filter, index ){
+ angular.extend( currentCol.filters[index], filter );
+ if ( typeof(filter.term) === 'undefined' || filter.term === null ){
+ delete currentCol.filters[index].term;
+ }
+ });
+ grid.api.core.raise.filterChanged();
+ }
+
+ if ( !!grid.api.pinning && grid.options.savePinning && currentCol.renderContainer !== columnState.pinned ){
+ grid.api.pinning.pinColumn(currentCol, columnState.pinned);
+ }
+
+ var currentIndex = grid.getOnlyDataColumns().indexOf( currentCol );
+ if (currentIndex !== -1) {
+ if (grid.options.saveOrder && currentIndex !== index) {
+ var column = grid.columns.splice(currentIndex + grid.rowHeaderColumns.length, 1)[0];
+ grid.columns.splice(index + grid.rowHeaderColumns.length, 0, column);
+ }
+ }
+ }
+ });
+
+ if ( isSortChanged ) {
+ grid.api.core.raise.sortChanged( grid, grid.getColumnSorting() );
+ }
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name restoreScrollFocus
+ * @methodOf ui.grid.saveState.service:uiGridSaveStateService
+ * @description Scrolls to the position that was saved. If focus is true, then
+ * sets focus to the specified row/col. If focus is false, then scrolls to the
+ * specified row/col.
+ *
+ * @param {Grid} grid the grid whose state we'd like to restore
+ * @param {scope} $scope a scope that we can broadcast on
+ * @param {object} scrollFocusState the scroll/focus state ready to be restored
+ */
+ restoreScrollFocus: function( grid, $scope, scrollFocusState ){
+ if ( !grid.api.cellNav ){
+ return;
+ }
+
+ var colDef, row;
+ if ( scrollFocusState.colName ){
+ var colDefs = grid.options.columnDefs.filter( function( colDef ) { return colDef.name === scrollFocusState.colName; });
+ if ( colDefs.length > 0 ){
+ colDef = colDefs[0];
+ }
+ }
+
+ if ( scrollFocusState.rowVal && scrollFocusState.rowVal.row ){
+ if ( scrollFocusState.rowVal.identity ){
+ row = service.findRowByIdentity( grid, scrollFocusState.rowVal );
+ } else {
+ row = grid.renderContainers.body.visibleRowCache[ scrollFocusState.rowVal.row ];
+ }
+ }
+
+ var entity = row && row.entity ? row.entity : null ;
+
+ if ( colDef || entity ) {
+ if (scrollFocusState.focus ){
+ grid.api.cellNav.scrollToFocus( entity, colDef );
+ } else {
+ grid.scrollTo( entity, colDef );
+ }
+ }
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name restoreSelection
+ * @methodOf ui.grid.saveState.service:uiGridSaveStateService
+ * @description Selects the rows that are provided in the selection
+ * state. If you are using `saveRowIdentity` and more than one row matches the identity
+ * function then only the first is selected.
+ * @param {Grid} grid the grid whose state we'd like to restore
+ * @param {object} selectionState the selection state ready to be restored
+ */
+ restoreSelection: function( grid, selectionState ){
+ if ( !grid.api.selection ){
+ return;
+ }
+
+ grid.api.selection.clearSelectedRows();
+
+ selectionState.forEach( function( rowVal ) {
+ if ( rowVal.identity ){
+ var foundRow = service.findRowByIdentity( grid, rowVal );
+
+ if ( foundRow ){
+ grid.api.selection.selectRow( foundRow.entity );
+ }
+
+ } else {
+ grid.api.selection.selectRowByVisibleIndex( rowVal.row );
+ }
+ });
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name restoreGrouping
+ * @methodOf ui.grid.saveState.service:uiGridSaveStateService
+ * @description Restores the grouping configuration, if the grouping feature
+ * is enabled.
+ * @param {Grid} grid the grid whose state we'd like to restore
+ * @param {object} groupingState the grouping state ready to be restored
+ */
+ restoreGrouping: function( grid, groupingState ){
+ if ( !grid.api.grouping || typeof(groupingState) === 'undefined' || groupingState === null || angular.equals(groupingState, {}) ){
+ return;
+ }
+
+ grid.api.grouping.setGrouping( groupingState );
+ },
+
+ /**
+ * @ngdoc function
+ * @name restoreTreeView
+ * @methodOf ui.grid.saveState.service:uiGridSaveStateService
+ * @description Restores the tree view configuration, if the tree view feature
+ * is enabled.
+ * @param {Grid} grid the grid whose state we'd like to restore
+ * @param {object} treeViewState the tree view state ready to be restored
+ */
+ restoreTreeView: function( grid, treeViewState ){
+ if ( !grid.api.treeView || typeof(treeViewState) === 'undefined' || treeViewState === null || angular.equals(treeViewState, {}) ){
+ return;
+ }
+
+ grid.api.treeView.setTreeView( treeViewState );
+ },
+
+ /**
+ * @ngdoc function
+ * @name restorePagination
+ * @methodOf ui.grid.saveState.service:uiGridSaveStateService
+ * @description Restores the pagination information, if pagination is enabled.
+ * @param {Grid} grid the grid whose state we'd like to restore
+ * @param {object} pagination the pagination object to be restored
+ * @param {number} pagination.paginationCurrentPage the page number to restore
+ * @param {number} pagination.paginationPageSize the number of items displayed per page
+ */
+ restorePagination: function( grid, pagination ){
+ if ( !grid.api.pagination || !grid.options.paginationPageSize ){
+ return;
+ }
+
+ grid.options.paginationCurrentPage = pagination.paginationCurrentPage;
+ grid.options.paginationPageSize = pagination.paginationPageSize;
+ },
+
+ /**
+ * @ngdoc function
+ * @name findRowByIdentity
+ * @methodOf ui.grid.saveState.service:uiGridSaveStateService
+ * @description Finds a row given it's identity value, returns the first found row
+ * if any are found, otherwise returns null if no rows are found.
+ * @param {Grid} grid the grid whose state we'd like to restore
+ * @param {object} rowVal the row we'd like to find
+ * @returns {gridRow} the found row, or null if none found
+ */
+ findRowByIdentity: function( grid, rowVal ){
+ if ( !grid.options.saveRowIdentity ){
+ return null;
+ }
+
+ var filteredRows = grid.rows.filter( function( gridRow ) {
+ if ( grid.options.saveRowIdentity( gridRow.entity ) === rowVal.row ){
+ return true;
+ } else {
+ return false;
+ }
+ });
+
+ if ( filteredRows.length > 0 ){
+ return filteredRows[0];
+ } else {
+ return null;
+ }
+ }
+ };
+
+ return service;
+
+ }
+ ]);
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.saveState.directive:uiGridSaveState
+ * @element div
+ * @restrict A
+ *
+ * @description Adds saveState features to grid
+ *
+ * @example
+
Defaults to true
+ */
+
+ /**
+ * @ngdoc object
+ * @name isSelected
+ * @propertyOf ui.grid.selection.api:GridRow
+ * @description Selected state of row. Should be readonly. Make any changes to selected state using setSelected().
+ *
Defaults to false
+ */
+
+
+ /**
+ * @ngdoc function
+ * @name setSelected
+ * @methodOf ui.grid.selection.api:GridRow
+ * @description Sets the isSelected property and updates the selectedCount
+ * Changes to isSelected state should only be made via this function
+ * @param {bool} selected value to set
+ */
+ $delegate.prototype.setSelected = function (selected) {
+ if (selected !== this.isSelected) {
+ this.isSelected = selected;
+ this.grid.selection.selectedCount += selected ? 1 : -1;
+ }
+ };
+
+ return $delegate;
+ }]);
+ }]);
+
+ /**
+ * @ngdoc service
+ * @name ui.grid.selection.service:uiGridSelectionService
+ *
+ * @description Services for selection features
+ */
+ module.service('uiGridSelectionService', ['$q', '$templateCache', 'uiGridSelectionConstants', 'gridUtil',
+ function ($q, $templateCache, uiGridSelectionConstants, gridUtil) {
+
+ var service = {
+
+ initializeGrid: function (grid) {
+
+ //add feature namespace and any properties to grid for needed
+ /**
+ * @ngdoc object
+ * @name ui.grid.selection.grid:selection
+ *
+ * @description Grid properties and functions added for selection
+ */
+ grid.selection = {};
+ grid.selection.lastSelectedRow = null;
+ grid.selection.selectAll = false;
+
+
+ /**
+ * @ngdoc object
+ * @name selectedCount
+ * @propertyOf ui.grid.selection.grid:selection
+ * @description Current count of selected rows
+ * @example
+ * var count = grid.selection.selectedCount
+ */
+ grid.selection.selectedCount = 0;
+
+ service.defaultGridOptions(grid.options);
+
+ /**
+ * @ngdoc object
+ * @name ui.grid.selection.api:PublicApi
+ *
+ * @description Public Api for selection feature
+ */
+ var publicApi = {
+ events: {
+ selection: {
+ /**
+ * @ngdoc event
+ * @name rowSelectionChanged
+ * @eventOf ui.grid.selection.api:PublicApi
+ * @description is raised after the row.isSelected state is changed
+ * @param {object} scope the scope associated with the grid
+ * @param {GridRow} row the row that was selected/deselected
+ * @param {Event} evt object if raised from an event
+ */
+ rowSelectionChanged: function (scope, row, evt) {
+ },
+ /**
+ * @ngdoc event
+ * @name rowSelectionChangedBatch
+ * @eventOf ui.grid.selection.api:PublicApi
+ * @description is raised after the row.isSelected state is changed
+ * in bulk, if the `enableSelectionBatchEvent` option is set to true
+ * (which it is by default). This allows more efficient processing
+ * of bulk events.
+ * @param {object} scope the scope associated with the grid
+ * @param {array} rows the rows that were selected/deselected
+ * @param {Event} evt object if raised from an event
+ */
+ rowSelectionChangedBatch: function (scope, rows, evt) {
+ }
+ }
+ },
+ methods: {
+ selection: {
+ /**
+ * @ngdoc function
+ * @name toggleRowSelection
+ * @methodOf ui.grid.selection.api:PublicApi
+ * @description Toggles data row as selected or unselected
+ * @param {object} rowEntity gridOptions.data[] array instance
+ * @param {Event} evt object if raised from an event
+ */
+ toggleRowSelection: function (rowEntity, evt) {
+ var row = grid.getRow(rowEntity);
+ if (row !== null) {
+ service.toggleRowSelection(grid, row, evt, grid.options.multiSelect, grid.options.noUnselect);
+ }
+ },
+ /**
+ * @ngdoc function
+ * @name selectRow
+ * @methodOf ui.grid.selection.api:PublicApi
+ * @description Select the data row
+ * @param {object} rowEntity gridOptions.data[] array instance
+ * @param {Event} evt object if raised from an event
+ */
+ selectRow: function (rowEntity, evt) {
+ var row = grid.getRow(rowEntity);
+ if (row !== null && !row.isSelected) {
+ service.toggleRowSelection(grid, row, evt, grid.options.multiSelect, grid.options.noUnselect);
+ }
+ },
+ /**
+ * @ngdoc function
+ * @name selectRowByVisibleIndex
+ * @methodOf ui.grid.selection.api:PublicApi
+ * @description Select the specified row by visible index (i.e. if you
+ * specify row 0 you'll get the first visible row selected). In this context
+ * visible means of those rows that are theoretically visible (i.e. not filtered),
+ * rather than rows currently rendered on the screen.
+ * @param {number} rowNum index within the rowsVisible array
+ * @param {Event} evt object if raised from an event
+ */
+ selectRowByVisibleIndex: function (rowNum, evt) {
+ var row = grid.renderContainers.body.visibleRowCache[rowNum];
+ if (row !== null && typeof (row) !== 'undefined' && !row.isSelected) {
+ service.toggleRowSelection(grid, row, evt, grid.options.multiSelect, grid.options.noUnselect);
+ }
+ },
+ /**
+ * @ngdoc function
+ * @name unSelectRow
+ * @methodOf ui.grid.selection.api:PublicApi
+ * @description UnSelect the data row
+ * @param {object} rowEntity gridOptions.data[] array instance
+ * @param {Event} evt object if raised from an event
+ */
+ unSelectRow: function (rowEntity, evt) {
+ var row = grid.getRow(rowEntity);
+ if (row !== null && row.isSelected) {
+ service.toggleRowSelection(grid, row, evt, grid.options.multiSelect, grid.options.noUnselect);
+ }
+ },
+ /**
+ * @ngdoc function
+ * @name unSelectRowByVisibleIndex
+ * @methodOf ui.grid.selection.api:PublicApi
+ * @description Unselect the specified row by visible index (i.e. if you
+ * specify row 0 you'll get the first visible row unselected). In this context
+ * visible means of those rows that are theoretically visible (i.e. not filtered),
+ * rather than rows currently rendered on the screen.
+ * @param {number} rowNum index within the rowsVisible array
+ * @param {Event} evt object if raised from an event
+ */
+ unSelectRowByVisibleIndex: function (rowNum, evt) {
+ var row = grid.renderContainers.body.visibleRowCache[rowNum];
+ if (row !== null && typeof (row) !== 'undefined' && row.isSelected) {
+ service.toggleRowSelection(grid, row, evt, grid.options.multiSelect, grid.options.noUnselect);
+ }
+ },
+ /**
+ * @ngdoc function
+ * @name selectAllRows
+ * @methodOf ui.grid.selection.api:PublicApi
+ * @description Selects all rows. Does nothing if multiSelect = false
+ * @param {Event} evt object if raised from an event
+ */
+ selectAllRows: function (evt) {
+ if (grid.options.multiSelect !== false) {
+ var changedRows = [];
+ grid.rows.forEach(function (row) {
+ if (!row.isSelected && row.enableSelection !== false && grid.options.isRowSelectable(row) !== false) {
+ row.setSelected(true);
+ service.decideRaiseSelectionEvent(grid, row, changedRows, evt);
+ }
+ });
+ grid.selection.selectAll = true;
+ service.decideRaiseSelectionBatchEvent(grid, changedRows, evt);
+ }
+ },
+ /**
+ * @ngdoc function
+ * @name selectAllVisibleRows
+ * @methodOf ui.grid.selection.api:PublicApi
+ * @description Selects all visible rows. Does nothing if multiSelect = false
+ * @param {Event} evt object if raised from an event
+ */
+ selectAllVisibleRows: function (evt) {
+ if (grid.options.multiSelect !== false) {
+ var changedRows = [];
+ grid.rows.forEach(function(row) {
+ if (row.visible) {
+ if (!row.isSelected && row.enableSelection !== false && grid.options.isRowSelectable(row) !== false) {
+ row.setSelected(true);
+ service.decideRaiseSelectionEvent(grid, row, changedRows, evt);
+ }
+ } else if (row.isSelected) {
+ row.setSelected(false);
+ service.decideRaiseSelectionEvent(grid, row, changedRows, evt);
+ }
+ });
+ grid.selection.selectAll = true;
+ service.decideRaiseSelectionBatchEvent(grid, changedRows, evt);
+ }
+ },
+ /**
+ * @ngdoc function
+ * @name clearSelectedRows
+ * @methodOf ui.grid.selection.api:PublicApi
+ * @description Unselects all rows
+ * @param {Event} evt object if raised from an event
+ */
+ clearSelectedRows: function (evt) {
+ service.clearSelectedRows(grid, evt);
+ },
+ /**
+ * @ngdoc function
+ * @name getSelectedRows
+ * @methodOf ui.grid.selection.api:PublicApi
+ * @description returns all selectedRow's entity references
+ */
+ getSelectedRows: function () {
+ return service.getSelectedRows(grid).map(function (gridRow) {
+ return gridRow.entity;
+ }).filter(function (entity) {
+ return entity.hasOwnProperty('$$hashKey') || !angular.isObject(entity);
+ });
+ },
+ /**
+ * @ngdoc function
+ * @name getSelectedGridRows
+ * @methodOf ui.grid.selection.api:PublicApi
+ * @description returns all selectedRow's as gridRows
+ */
+ getSelectedGridRows: function () {
+ return service.getSelectedRows(grid);
+ },
+ /**
+ * @ngdoc function
+ * @name getSelectedCount
+ * @methodOf ui.grid.selection.api:PublicApi
+ * @description returns the number of rows selected
+ */
+ getSelectedCount: function () {
+ return grid.selection.selectedCount;
+ },
+ /**
+ * @ngdoc function
+ * @name setMultiSelect
+ * @methodOf ui.grid.selection.api:PublicApi
+ * @description Sets the current gridOption.multiSelect to true or false
+ * @param {bool} multiSelect true to allow multiple rows
+ */
+ setMultiSelect: function (multiSelect) {
+ grid.options.multiSelect = multiSelect;
+ },
+ /**
+ * @ngdoc function
+ * @name setModifierKeysToMultiSelect
+ * @methodOf ui.grid.selection.api:PublicApi
+ * @description Sets the current gridOption.modifierKeysToMultiSelect to true or false
+ * @param {bool} modifierKeysToMultiSelect true to only allow multiple rows when using ctrlKey or shiftKey is used
+ */
+ setModifierKeysToMultiSelect: function (modifierKeysToMultiSelect) {
+ grid.options.modifierKeysToMultiSelect = modifierKeysToMultiSelect;
+ },
+ /**
+ * @ngdoc function
+ * @name getSelectAllState
+ * @methodOf ui.grid.selection.api:PublicApi
+ * @description Returns whether or not the selectAll checkbox is currently ticked. The
+ * grid doesn't automatically select rows when you add extra data - so when you add data
+ * you need to explicitly check whether the selectAll is set, and then call setVisible rows
+ * if it is
+ */
+ getSelectAllState: function () {
+ return grid.selection.selectAll;
+ }
+
+ }
+ }
+ };
+
+ grid.api.registerEventsFromObject(publicApi.events);
+
+ grid.api.registerMethodsFromObject(publicApi.methods);
+
+ },
+
+ defaultGridOptions: function (gridOptions) {
+ //default option to true unless it was explicitly set to false
+ /**
+ * @ngdoc object
+ * @name ui.grid.selection.api:GridOptions
+ *
+ * @description GridOptions for selection feature, these are available to be
+ * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
+ */
+
+ /**
+ * @ngdoc object
+ * @name enableRowSelection
+ * @propertyOf ui.grid.selection.api:GridOptions
+ * @description Enable row selection for entire grid.
+ *
Defaults to true
+ */
+ gridOptions.enableRowSelection = gridOptions.enableRowSelection !== false;
+ /**
+ * @ngdoc object
+ * @name multiSelect
+ * @propertyOf ui.grid.selection.api:GridOptions
+ * @description Enable multiple row selection for entire grid
+ *
Defaults to true
+ */
+ gridOptions.multiSelect = gridOptions.multiSelect !== false;
+ /**
+ * @ngdoc object
+ * @name noUnselect
+ * @propertyOf ui.grid.selection.api:GridOptions
+ * @description Prevent a row from being unselected. Works in conjunction
+ * with `multiselect = false` and `gridApi.selection.selectRow()` to allow
+ * you to create a single selection only grid - a row is always selected, you
+ * can only select different rows, you can't unselect the row.
+ *
Defaults to false
+ */
+ gridOptions.noUnselect = gridOptions.noUnselect === true;
+ /**
+ * @ngdoc object
+ * @name modifierKeysToMultiSelect
+ * @propertyOf ui.grid.selection.api:GridOptions
+ * @description Enable multiple row selection only when using the ctrlKey or shiftKey. Requires multiSelect to be true.
+ *
Defaults to false
+ */
+ gridOptions.modifierKeysToMultiSelect = gridOptions.modifierKeysToMultiSelect === true;
+ /**
+ * @ngdoc object
+ * @name enableRowHeaderSelection
+ * @propertyOf ui.grid.selection.api:GridOptions
+ * @description Enable a row header to be used for selection
+ *
Defaults to true
+ */
+ gridOptions.enableRowHeaderSelection = gridOptions.enableRowHeaderSelection !== false;
+ /**
+ * @ngdoc object
+ * @name enableFullRowSelection
+ * @propertyOf ui.grid.selection.api:GridOptions
+ * @description Enable selection by clicking anywhere on the row. Defaults to
+ * false if `enableRowHeaderSelection` is true, otherwise defaults to false.
+ */
+ if (typeof (gridOptions.enableFullRowSelection) === 'undefined') {
+ gridOptions.enableFullRowSelection = !gridOptions.enableRowHeaderSelection;
+ }
+ /**
+ * @ngdoc object
+ * @name enableSelectAll
+ * @propertyOf ui.grid.selection.api:GridOptions
+ * @description Enable the select all checkbox at the top of the selectionRowHeader
+ *
Defaults to true
+ */
+ gridOptions.enableSelectAll = gridOptions.enableSelectAll !== false;
+ /**
+ * @ngdoc object
+ * @name enableSelectionBatchEvent
+ * @propertyOf ui.grid.selection.api:GridOptions
+ * @description If selected rows are changed in bulk, either via the API or
+ * via the selectAll checkbox, then a separate event is fired. Setting this
+ * option to false will cause the rowSelectionChanged event to be called multiple times
+ * instead
+ *
Defaults to true
+ */
+ gridOptions.enableSelectionBatchEvent = gridOptions.enableSelectionBatchEvent !== false;
+ /**
+ * @ngdoc object
+ * @name selectionRowHeaderWidth
+ * @propertyOf ui.grid.selection.api:GridOptions
+ * @description can be used to set a custom width for the row header selection column
+ *
Defaults to 30px
+ */
+ gridOptions.selectionRowHeaderWidth = angular.isDefined(gridOptions.selectionRowHeaderWidth) ? gridOptions.selectionRowHeaderWidth : 30;
+
+ /**
+ * @ngdoc object
+ * @name enableFooterTotalSelected
+ * @propertyOf ui.grid.selection.api:GridOptions
+ * @description Shows the total number of selected items in footer if true.
+ *
Defaults to true.
+ *
GridOptions.showGridFooter must also be set to true.
+ */
+ gridOptions.enableFooterTotalSelected = gridOptions.enableFooterTotalSelected !== false;
+
+ /**
+ * @ngdoc object
+ * @name isRowSelectable
+ * @propertyOf ui.grid.selection.api:GridOptions
+ * @description Makes it possible to specify a method that evaluates for each row and sets its "enableSelection" property.
+ */
+
+ gridOptions.isRowSelectable = angular.isDefined(gridOptions.isRowSelectable) ? gridOptions.isRowSelectable : angular.noop;
+ },
+
+ /**
+ * @ngdoc function
+ * @name toggleRowSelection
+ * @methodOf ui.grid.selection.service:uiGridSelectionService
+ * @description Toggles row as selected or unselected
+ * @param {Grid} grid grid object
+ * @param {GridRow} row row to select or deselect
+ * @param {Event} evt object if resulting from event
+ * @param {bool} multiSelect if false, only one row at time can be selected
+ * @param {bool} noUnselect if true then rows cannot be unselected
+ */
+ toggleRowSelection: function (grid, row, evt, multiSelect, noUnselect) {
+ var selected = row.isSelected;
+
+ if (row.enableSelection === false) {
+ return;
+ }
+
+ var selectedRows;
+ if (!multiSelect && !selected) {
+ service.clearSelectedRows(grid, evt);
+ } else if (!multiSelect && selected) {
+ selectedRows = service.getSelectedRows(grid);
+ if (selectedRows.length > 1) {
+ selected = false; // Enable reselect of the row
+ service.clearSelectedRows(grid, evt);
+ }
+ }
+
+ if (selected && noUnselect) {
+ // don't deselect the row
+ } else {
+ row.setSelected(!selected);
+ if (row.isSelected === true) {
+ grid.selection.lastSelectedRow = row;
+ }
+
+ selectedRows = service.getSelectedRows(grid);
+ grid.selection.selectAll = grid.rows.length === selectedRows.length;
+
+ grid.api.selection.raise.rowSelectionChanged(row, evt);
+ }
+ },
+ /**
+ * @ngdoc function
+ * @name shiftSelect
+ * @methodOf ui.grid.selection.service:uiGridSelectionService
+ * @description selects a group of rows from the last selected row using the shift key
+ * @param {Grid} grid grid object
+ * @param {GridRow} row clicked row
+ * @param {Event} evt object if raised from an event
+ * @param {bool} multiSelect if false, does nothing this is for multiSelect only
+ */
+ shiftSelect: function (grid, row, evt, multiSelect) {
+ if (!multiSelect) {
+ return;
+ }
+ var selectedRows = service.getSelectedRows(grid);
+ var fromRow = selectedRows.length > 0 ? grid.renderContainers.body.visibleRowCache.indexOf(grid.selection.lastSelectedRow) : 0;
+ var toRow = grid.renderContainers.body.visibleRowCache.indexOf(row);
+ //reverse select direction
+ if (fromRow > toRow) {
+ var tmp = fromRow;
+ fromRow = toRow;
+ toRow = tmp;
+ }
+
+ var changedRows = [];
+ for (var i = fromRow; i <= toRow; i++) {
+ var rowToSelect = grid.renderContainers.body.visibleRowCache[i];
+ if (rowToSelect) {
+ if (!rowToSelect.isSelected && rowToSelect.enableSelection !== false) {
+ rowToSelect.setSelected(true);
+ grid.selection.lastSelectedRow = rowToSelect;
+ service.decideRaiseSelectionEvent(grid, rowToSelect, changedRows, evt);
+ }
+ }
+ }
+ service.decideRaiseSelectionBatchEvent(grid, changedRows, evt);
+ },
+ /**
+ * @ngdoc function
+ * @name getSelectedRows
+ * @methodOf ui.grid.selection.service:uiGridSelectionService
+ * @description Returns all the selected rows
+ * @param {Grid} grid grid object
+ */
+ getSelectedRows: function (grid) {
+ return grid.rows.filter(function (row) {
+ return row.isSelected;
+ });
+ },
+
+ /**
+ * @ngdoc function
+ * @name clearSelectedRows
+ * @methodOf ui.grid.selection.service:uiGridSelectionService
+ * @description Clears all selected rows
+ * @param {Grid} grid grid object
+ * @param {Event} evt object if raised from an event
+ */
+ clearSelectedRows: function (grid, evt) {
+ var changedRows = [];
+ service.getSelectedRows(grid).forEach(function (row) {
+ if (row.isSelected) {
+ row.setSelected(false);
+ service.decideRaiseSelectionEvent(grid, row, changedRows, evt);
+ }
+ });
+ grid.selection.selectAll = false;
+ grid.selection.selectedCount = 0;
+ service.decideRaiseSelectionBatchEvent(grid, changedRows, evt);
+ },
+
+ /**
+ * @ngdoc function
+ * @name decideRaiseSelectionEvent
+ * @methodOf ui.grid.selection.service:uiGridSelectionService
+ * @description Decides whether to raise a single event or a batch event
+ * @param {Grid} grid grid object
+ * @param {GridRow} row row that has changed
+ * @param {array} changedRows an array to which we can append the changed
+ * @param {Event} evt object if raised from an event
+ * row if we're doing batch events
+ */
+ decideRaiseSelectionEvent: function (grid, row, changedRows, evt) {
+ if (!grid.options.enableSelectionBatchEvent) {
+ grid.api.selection.raise.rowSelectionChanged(row, evt);
+ } else {
+ changedRows.push(row);
+ }
+ },
+
+ /**
+ * @ngdoc function
+ * @name raiseSelectionEvent
+ * @methodOf ui.grid.selection.service:uiGridSelectionService
+ * @description Decides whether we need to raise a batch event, and
+ * raises it if we do.
+ * @param {Grid} grid grid object
+ * @param {array} changedRows an array of changed rows, only populated
+ * @param {Event} evt object if raised from an event
+ * if we're doing batch events
+ */
+ decideRaiseSelectionBatchEvent: function (grid, changedRows, evt) {
+ if (changedRows.length > 0) {
+ grid.api.selection.raise.rowSelectionChangedBatch(changedRows, evt);
+ }
+ }
+ };
+
+ return service;
+
+ }]);
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.selection.directive:uiGridSelection
+ * @element div
+ * @restrict A
+ *
+ * @description Adds selection features to grid
+ *
+ * @example
+
+ *
+ *
+ *
+ */
+
+ var module = angular.module('ui.grid.treeBase', ['ui.grid']);
+
+ /**
+ * @ngdoc object
+ * @name ui.grid.treeBase.constant:uiGridTreeBaseConstants
+ *
+ * @description constants available in treeBase module.
+ *
+ * These constants are manually copied into grouping and treeView,
+ * as I haven't found a way to simply include them, and it's not worth
+ * investing time in for something that changes very infrequently.
+ *
+ */
+ module.constant('uiGridTreeBaseConstants', {
+ featureName: "treeBase",
+ rowHeaderColName: 'treeBaseRowHeaderCol',
+ EXPANDED: 'expanded',
+ COLLAPSED: 'collapsed',
+ aggregation: {
+ COUNT: 'count',
+ SUM: 'sum',
+ MAX: 'max',
+ MIN: 'min',
+ AVG: 'avg'
+ }
+ });
+
+ /**
+ * @ngdoc service
+ * @name ui.grid.treeBase.service:uiGridTreeBaseService
+ *
+ * @description Services for treeBase feature
+ */
+ /**
+ * @ngdoc object
+ * @name ui.grid.treeBase.api:ColumnDef
+ *
+ * @description ColumnDef for tree feature, these are available to be
+ * set using the ui-grid {@link ui.grid.class:GridOptions.columnDef gridOptions.columnDefs}
+ */
+
+ module.service('uiGridTreeBaseService', ['$q', 'uiGridTreeBaseConstants', 'gridUtil', 'GridRow', 'gridClassFactory', 'i18nService', 'uiGridConstants', 'rowSorter',
+ function ($q, uiGridTreeBaseConstants, gridUtil, GridRow, gridClassFactory, i18nService, uiGridConstants, rowSorter) {
+
+ var service = {
+
+ initializeGrid: function (grid, $scope) {
+
+ //add feature namespace and any properties to grid for needed
+ /**
+ * @ngdoc object
+ * @name ui.grid.treeBase.grid:treeBase
+ *
+ * @description Grid properties and functions added for treeBase
+ */
+ grid.treeBase = {};
+
+ /**
+ * @ngdoc property
+ * @propertyOf ui.grid.treeBase.grid:treeBase
+ * @name numberLevels
+ *
+ * @description Total number of tree levels currently used, calculated by the rowsProcessor by
+ * retaining the highest tree level it sees
+ */
+ grid.treeBase.numberLevels = 0;
+
+ /**
+ * @ngdoc property
+ * @propertyOf ui.grid.treeBase.grid:treeBase
+ * @name expandAll
+ *
+ * @description Whether or not the expandAll box is selected
+ */
+ grid.treeBase.expandAll = false;
+
+ /**
+ * @ngdoc property
+ * @propertyOf ui.grid.treeBase.grid:treeBase
+ * @name tree
+ *
+ * @description Tree represented as a nested array that holds the state of each node, along with a
+ * pointer to the row. The array order is material - we will display the children in the order
+ * they are stored in the array
+ *
+ * Each node stores:
+ *
+ * - the state of this node
+ * - an array of children of this node
+ * - a pointer to the parent of this node (reverse pointer, allowing us to walk up the tree)
+ * - the number of children of this node
+ * - aggregation information calculated from the nodes
+ *
+ * ```
+ * [{
+ * state: 'expanded',
+ * row:
+ * gridApi.treeBase.on.rowExpanded(scope,function(row){})
+ *
+ * @param {gridRow} row the row that was expanded. You can also
+ * retrieve the grid from this row with row.grid
+ */
+ rowExpanded: {},
+
+ /**
+ * @ngdoc event
+ * @eventOf ui.grid.treeBase.api:PublicApi
+ * @name rowCollapsed
+ * @description raised whenever a row is collapsed. Doesn't really have
+ * a purpose at the moment, included for symmetry
+ *
+ *
+ * gridApi.treeBase.on.rowCollapsed(scope,function(row){})
+ *
+ * @param {gridRow} row the row that was collapsed. You can also
+ * retrieve the grid from this row with row.grid
+ */
+ rowCollapsed: {}
+ }
+ },
+
+ methods: {
+ treeBase: {
+ /**
+ * @ngdoc function
+ * @name expandAllRows
+ * @methodOf ui.grid.treeBase.api:PublicApi
+ * @description Expands all tree rows
+ */
+ expandAllRows: function () {
+ service.expandAllRows(grid);
+ },
+
+ /**
+ * @ngdoc function
+ * @name collapseAllRows
+ * @methodOf ui.grid.treeBase.api:PublicApi
+ * @description collapse all tree rows
+ */
+ collapseAllRows: function () {
+ service.collapseAllRows(grid);
+ },
+
+ /**
+ * @ngdoc function
+ * @name toggleRowTreeState
+ * @methodOf ui.grid.treeBase.api:PublicApi
+ * @description call expand if the row is collapsed, collapse if it is expanded
+ * @param {gridRow} row the row you wish to toggle
+ */
+ toggleRowTreeState: function (row) {
+ service.toggleRowTreeState(grid, row);
+ },
+
+ /**
+ * @ngdoc function
+ * @name expandRow
+ * @methodOf ui.grid.treeBase.api:PublicApi
+ * @description expand the immediate children of the specified row
+ * @param {gridRow} row the row you wish to expand
+ * @param {boolean} recursive true if you wish to expand the row's ancients
+ */
+ expandRow: function (row, recursive) {
+ service.expandRow(grid, row, recursive);
+ },
+
+ /**
+ * @ngdoc function
+ * @name expandRowChildren
+ * @methodOf ui.grid.treeBase.api:PublicApi
+ * @description expand all children of the specified row
+ * @param {gridRow} row the row you wish to expand
+ */
+ expandRowChildren: function (row) {
+ service.expandRowChildren(grid, row);
+ },
+
+ /**
+ * @ngdoc function
+ * @name collapseRow
+ * @methodOf ui.grid.treeBase.api:PublicApi
+ * @description collapse the specified row. When
+ * you expand the row again, all grandchildren will retain their state
+ * @param {gridRow} row the row you wish to collapse
+ */
+ collapseRow: function ( row ) {
+ service.collapseRow(grid, row);
+ },
+
+ /**
+ * @ngdoc function
+ * @name collapseRowChildren
+ * @methodOf ui.grid.treeBase.api:PublicApi
+ * @description collapse all children of the specified row. When
+ * you expand the row again, all grandchildren will be collapsed
+ * @param {gridRow} row the row you wish to collapse children for
+ */
+ collapseRowChildren: function ( row ) {
+ service.collapseRowChildren(grid, row);
+ },
+
+ /**
+ * @ngdoc function
+ * @name getTreeState
+ * @methodOf ui.grid.treeBase.api:PublicApi
+ * @description Get the tree state for this grid,
+ * used by the saveState feature
+ * Returned treeState as an object
+ * `{ expandedState: { uid: 'expanded', uid: 'collapsed' } }`
+ * where expandedState is a hash of row uid and the current expanded state
+ *
+ * @returns {object} tree state
+ *
+ * TODO - this needs work - we need an identifier that persists across instantiations,
+ * not uid. This really means we need a row identity defined, but that won't work for
+ * grouping. Perhaps this needs to be moved up to treeView and grouping, rather than
+ * being in base.
+ */
+ getTreeExpandedState: function () {
+ return { expandedState: service.getTreeState(grid) };
+ },
+
+ /**
+ * @ngdoc function
+ * @name setTreeState
+ * @methodOf ui.grid.treeBase.api:PublicApi
+ * @description Set the expanded states of the tree
+ * @param {object} config the config you want to apply, in the format
+ * provided by getTreeState
+ */
+ setTreeState: function ( config ) {
+ service.setTreeState( grid, config );
+ },
+
+ /**
+ * @ngdoc function
+ * @name getRowChildren
+ * @methodOf ui.grid.treeBase.api:PublicApi
+ * @description Get the children of the specified row
+ * @param {GridRow} row the row you want the children of
+ * @returns {Array} array of children of this row, the children
+ * are all gridRows
+ */
+ getRowChildren: function ( row ){
+ return row.treeNode.children.map( function( childNode ){
+ return childNode.row;
+ });
+ }
+ }
+ }
+ };
+
+ grid.api.registerEventsFromObject(publicApi.events);
+
+ grid.api.registerMethodsFromObject(publicApi.methods);
+ },
+
+
+ defaultGridOptions: function (gridOptions) {
+ //default option to true unless it was explicitly set to false
+ /**
+ * @ngdoc object
+ * @name ui.grid.treeBase.api:GridOptions
+ *
+ * @description GridOptions for treeBase feature, these are available to be
+ * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
+ */
+
+ /**
+ * @ngdoc object
+ * @name treeRowHeaderBaseWidth
+ * @propertyOf ui.grid.treeBase.api:GridOptions
+ * @description Base width of the tree header, provides for a single level of tree. This
+ * is incremented by `treeIndent` for each extra level
+ *
Defaults to 30
+ */
+ gridOptions.treeRowHeaderBaseWidth = gridOptions.treeRowHeaderBaseWidth || 30;
+
+ /**
+ * @ngdoc object
+ * @name treeIndent
+ * @propertyOf ui.grid.treeBase.api:GridOptions
+ * @description Number of pixels of indent for the icon at each tree level, wider indents are visually more pleasing,
+ * but will make the tree row header wider
+ *
Defaults to 10
+ */
+ gridOptions.treeIndent = (gridOptions.treeIndent != null) ? gridOptions.treeIndent : 10;
+
+ /**
+ * @ngdoc object
+ * @name showTreeRowHeader
+ * @propertyOf ui.grid.treeBase.api:GridOptions
+ * @description If set to false, don't create the row header. You'll need to programmatically control the expand
+ * states
+ *
Defaults to true
+ */
+ gridOptions.showTreeRowHeader = gridOptions.showTreeRowHeader !== false;
+
+ /**
+ * @ngdoc object
+ * @name showTreeExpandNoChildren
+ * @propertyOf ui.grid.treeBase.api:GridOptions
+ * @description If set to true, show the expand/collapse button even if there are no
+ * children of a node. You'd use this if you're planning to dynamically load the children
+ *
+ *
Defaults to true, grouping overrides to false
+ */
+ gridOptions.showTreeExpandNoChildren = gridOptions.showTreeExpandNoChildren !== false;
+
+ /**
+ * @ngdoc object
+ * @name treeRowHeaderAlwaysVisible
+ * @propertyOf ui.grid.treeBase.api:GridOptions
+ * @description If set to true, row header even if there are no tree nodes
+ *
+ *
Defaults to true
+ */
+ gridOptions.treeRowHeaderAlwaysVisible = gridOptions.treeRowHeaderAlwaysVisible !== false;
+
+ /**
+ * @ngdoc object
+ * @name treeCustomAggregations
+ * @propertyOf ui.grid.treeBase.api:GridOptions
+ * @description Define custom aggregation functions. The properties of this object will be
+ * aggregation types available for use on columnDef with {@link ui.grid.treeBase.api:ColumnDef treeAggregationType} or through the column menu.
+ * If a function defined here uses the same name as one of the native aggregations, this one will take precedence.
+ * The object format is:
+ *
+ *
+ * {
+ * aggregationName: {
+ * label: (optional) string,
+ * aggregationFn: function( aggregation, fieldValue, numValue, row ){...},
+ * finalizerFn: (optional) function( aggregation ){...}
+ * },
+ * mean: {
+ * label: 'mean',
+ * aggregationFn: function( aggregation, fieldValue, numValue ){
+ * aggregation.count = (aggregation.count || 1) + 1;
+ * aggregation.sum = (aggregation.sum || 0) + numValue;
+ * },
+ * finalizerFn: function( aggregation ){
+ * aggregation.value = aggregation.sum / aggregation.count
+ * }
+ * }
+ * }
+ *
+ *
+ *
The `finalizerFn` may be used to manipulate the value before rendering, or to
+ * apply a custom rendered value. If `aggregation.rendered` is left undefined, the value will be
+ * rendered. Note that the native aggregation functions use an `finalizerFn` to concatenate
+ * the label and the value.
+ *
+ *
Defaults to {}
+ */
+ gridOptions.treeCustomAggregations = gridOptions.treeCustomAggregations || {};
+
+ /**
+ * @ngdoc object
+ * @name enableExpandAll
+ * @propertyOf ui.grid.treeBase.api:GridOptions
+ * @description Enable the expand all button at the top of the row header
+ *
+ *
Defaults to true
+ */
+ gridOptions.enableExpandAll = gridOptions.enableExpandAll !== false;
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name treeBaseColumnBuilder
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Sets the tree defaults based on the columnDefs
+ *
+ * @param {object} colDef columnDef we're basing on
+ * @param {GridColumn} col the column we're to update
+ * @param {object} gridOptions the options we should use
+ * @returns {promise} promise for the builder - actually we do it all inline so it's immediately resolved
+ */
+ treeBaseColumnBuilder: function (colDef, col, gridOptions) {
+
+
+ /**
+ * @ngdoc object
+ * @name customTreeAggregationFn
+ * @propertyOf ui.grid.treeBase.api:ColumnDef
+ * @description A custom function that aggregates rows into some form of
+ * total. Aggregations run row-by-row, the function needs to be capable of
+ * creating a running total.
+ *
+ * The function will be provided the aggregation item (in which you can store running
+ * totals), the row value that is to be aggregated, and that same row value converted to
+ * a number (most aggregations work on numbers)
+ * @example
+ *
+ * customTreeAggregationFn = function ( aggregation, fieldValue, numValue, row ){
+ * // calculates the average of the squares of the values
+ * if ( typeof(aggregation.count) === 'undefined' ){
+ * aggregation.count = 0;
+ * }
+ * aggregation.count++;
+ *
+ * if ( !isNaN(numValue) ){
+ * if ( typeof(aggregation.total) === 'undefined' ){
+ * aggregation.total = 0;
+ * }
+ * aggregation.total = aggregation.total + numValue * numValue;
+ * }
+ *
+ * aggregation.value = aggregation.total / aggregation.count;
+ * }
+ *
+ *
Defaults to undefined. May be overwritten by treeAggregationType, the two options should not be used together.
+ */
+ if ( typeof(colDef.customTreeAggregationFn) !== 'undefined' ){
+ col.treeAggregationFn = colDef.customTreeAggregationFn;
+ }
+
+ /**
+ * @ngdoc object
+ * @name treeAggregationType
+ * @propertyOf ui.grid.treeBase.api:ColumnDef
+ * @description Use one of the native or grid-level aggregation methods for calculating aggregations on this column.
+ * Native method are in the constants file and include: SUM, COUNT, MIN, MAX, AVG. This may also be the property the
+ * name of an aggregation function defined with {@link ui.grid.treeBase.api:GridOptions treeCustomAggregations}.
+ *
+ *
+ * treeAggregationType = uiGridTreeBaseConstants.aggregation.SUM,
+ * }
+ *
+ *
+ * If you are using aggregations you should either:
+ *
+ * - also use grouping, in which case the aggregations are displayed in the group header, OR
+ * - use treeView, in which case you can set `treeAggregationUpdateEntity: true` in the colDef, and
+ * treeBase will store the aggregation information in the entity, or you can set `treeAggregationUpdateEntity: false`
+ * in the colDef, and you need to manual retrieve the calculated aggregations from the row.treeNode.aggregations
+ *
+ *
Takes precendence over a treeAggregationFn, the two options should not be used together.
+ *
Defaults to undefined.
+ */
+ if ( typeof(colDef.treeAggregationType) !== 'undefined' ){
+ col.treeAggregation = { type: colDef.treeAggregationType };
+ if ( typeof(gridOptions.treeCustomAggregations[colDef.treeAggregationType]) !== 'undefined' ){
+ col.treeAggregationFn = gridOptions.treeCustomAggregations[colDef.treeAggregationType].aggregationFn;
+ col.treeAggregationFinalizerFn = gridOptions.treeCustomAggregations[colDef.treeAggregationType].finalizerFn;
+ col.treeAggregation.label = gridOptions.treeCustomAggregations[colDef.treeAggregationType].label;
+ } else if ( typeof(service.nativeAggregations()[colDef.treeAggregationType]) !== 'undefined' ){
+ col.treeAggregationFn = service.nativeAggregations()[colDef.treeAggregationType].aggregationFn;
+ col.treeAggregation.label = service.nativeAggregations()[colDef.treeAggregationType].label;
+ }
+ }
+
+ /**
+ * @ngdoc object
+ * @name treeAggregationLabel
+ * @propertyOf ui.grid.treeBase.api:ColumnDef
+ * @description A custom label to use for this aggregation. If provided we don't use native i18n.
+ */
+ if ( typeof(colDef.treeAggregationLabel) !== 'undefined' ){
+ if (typeof(col.treeAggregation) === 'undefined' ){
+ col.treeAggregation = {};
+ }
+ col.treeAggregation.label = colDef.treeAggregationLabel;
+ }
+
+ /**
+ * @ngdoc object
+ * @name treeAggregationUpdateEntity
+ * @propertyOf ui.grid.treeBase.api:ColumnDef
+ * @description Store calculated aggregations into the entity, allowing them
+ * to be displayed in the grid using a standard cellTemplate. This defaults to true,
+ * if you are using grouping then you shouldn't set it to false, as then the aggregations won't
+ * display.
+ *
+ * If you are using treeView in most cases you'll want to set this to true. This will result in
+ * getCellValue returning the aggregation rather than whatever was stored in the cell attribute on
+ * the entity. If you want to render the underlying entity value (and do something else with the aggregation)
+ * then you could use a custom cellTemplate to display `row.entity.myAttribute`, rather than using getCellValue.
+ *
+ *
Defaults to true
+ *
+ * @example
+ *
+ * gridOptions.columns = [{
+ * name: 'myCol',
+ * treeAggregation: { type: uiGridTreeBaseConstants.aggregation.SUM },
+ * treeAggregationUpdateEntity: true
+ * cellTemplate: '
+ */
+ col.treeAggregationUpdateEntity = colDef.treeAggregationUpdateEntity !== false;
+
+ /**
+ * @ngdoc object
+ * @name customTreeAggregationFinalizerFn
+ * @propertyOf ui.grid.treeBase.api:ColumnDef
+ * @description A custom function that populates aggregation.rendered, this is called when
+ * a particular aggregation has been fully calculated, and we want to render the value.
+ *
+ * With the native aggregation options we just concatenate `aggregation.label` and
+ * `aggregation.value`, but if you wanted to apply a filter or otherwise manipulate the label
+ * or the value, you can do so with this function. This function will be called after the
+ * the default `finalizerFn`.
+ *
+ * @example
+ *
+ * customTreeAggregationFinalizerFn = function ( aggregation ){
+ * aggregation.rendered = aggregation.label + aggregation.value / 100 + '%';
+ * }
+ *
+ *
Defaults to undefined.
+ */
+ if ( typeof(col.customTreeAggregationFinalizerFn) === 'undefined' ){
+ col.customTreeAggregationFinalizerFn = colDef.customTreeAggregationFinalizerFn;
+ }
+
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name createRowHeader
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Create the rowHeader. If treeRowHeaderAlwaysVisible then
+ * set it to visible, otherwise set it to invisible
+ *
+ * @param {Grid} grid grid object
+ */
+ createRowHeader: function( grid ){
+ var rowHeaderColumnDef = {
+ name: uiGridTreeBaseConstants.rowHeaderColName,
+ displayName: '',
+ width: grid.options.treeRowHeaderBaseWidth,
+ minWidth: 10,
+ cellTemplate: 'ui-grid/treeBaseRowHeader',
+ headerCellTemplate: 'ui-grid/treeBaseHeaderCell',
+ enableColumnResizing: false,
+ enableColumnMenu: false,
+ exporterSuppressExport: true,
+ allowCellFocus: true
+ };
+
+ rowHeaderColumnDef.visible = grid.options.treeRowHeaderAlwaysVisible;
+ grid.addRowHeaderColumn(rowHeaderColumnDef, -100);
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name expandAllRows
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Expands all nodes in the tree
+ *
+ * @param {Grid} grid grid object
+ */
+ expandAllRows: function (grid) {
+ grid.treeBase.tree.forEach( function( node ) {
+ service.setAllNodes( grid, node, uiGridTreeBaseConstants.EXPANDED);
+ });
+ grid.treeBase.expandAll = true;
+ grid.queueGridRefresh();
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name collapseAllRows
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Collapses all nodes in the tree
+ *
+ * @param {Grid} grid grid object
+ */
+ collapseAllRows: function (grid) {
+ grid.treeBase.tree.forEach( function( node ) {
+ service.setAllNodes( grid, node, uiGridTreeBaseConstants.COLLAPSED);
+ });
+ grid.treeBase.expandAll = false;
+ grid.queueGridRefresh();
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name setAllNodes
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Works through a subset of grid.treeBase.rowExpandedStates, setting
+ * all child nodes (and their descendents) of the provided node to the given state.
+ *
+ * Calls itself recursively on all nodes so as to achieve this.
+ *
+ * @param {Grid} grid the grid we're operating on (so we can raise events)
+ * @param {object} treeNode a node in the tree that we want to update
+ * @param {string} targetState the state we want to set it to
+ */
+ setAllNodes: function (grid, treeNode, targetState) {
+ if ( typeof(treeNode.state) !== 'undefined' && treeNode.state !== targetState ){
+ treeNode.state = targetState;
+
+ if ( targetState === uiGridTreeBaseConstants.EXPANDED ){
+ grid.api.treeBase.raise.rowExpanded(treeNode.row);
+ } else {
+ grid.api.treeBase.raise.rowCollapsed(treeNode.row);
+ }
+ }
+
+ // set all child nodes
+ if ( treeNode.children ){
+ treeNode.children.forEach(function( childNode ){
+ service.setAllNodes(grid, childNode, targetState);
+ });
+ }
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name toggleRowTreeState
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Toggles the expand or collapse state of this grouped row, if
+ * it's a parent row
+ *
+ * @param {Grid} grid grid object
+ * @param {GridRow} row the row we want to toggle
+ */
+ toggleRowTreeState: function ( grid, row ){
+ if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){
+ return;
+ }
+
+ if (row.treeNode.state === uiGridTreeBaseConstants.EXPANDED){
+ service.collapseRow(grid, row);
+ } else {
+ service.expandRow(grid, row, false);
+ }
+
+ grid.queueGridRefresh();
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name expandRow
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Expands this specific row, showing only immediate children.
+ *
+ * @param {Grid} grid grid object
+ * @param {GridRow} row the row we want to expand
+ * @param {boolean} recursive true if you wish to expand the row's ancients
+ */
+ expandRow: function ( grid, row, recursive ){
+ if ( recursive ){
+ var parents = [];
+ while ( row && typeof(row.treeLevel) !== 'undefined' && row.treeLevel !== null && row.treeLevel >= 0 && row.treeNode.state !== uiGridTreeBaseConstants.EXPANDED ){
+ parents.push(row);
+ row = row.treeNode.parentRow;
+ }
+
+ if ( parents.length > 0 ){
+ row = parents.pop();
+ while ( row ){
+ row.treeNode.state = uiGridTreeBaseConstants.EXPANDED;
+ grid.api.treeBase.raise.rowExpanded(row);
+ row = parents.pop();
+ }
+
+ grid.treeBase.expandAll = service.allExpanded(grid.treeBase.tree);
+ grid.queueGridRefresh();
+ }
+ } else {
+ if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){
+ return;
+ }
+
+ if ( row.treeNode.state !== uiGridTreeBaseConstants.EXPANDED ){
+ row.treeNode.state = uiGridTreeBaseConstants.EXPANDED;
+ grid.api.treeBase.raise.rowExpanded(row);
+ grid.treeBase.expandAll = service.allExpanded(grid.treeBase.tree);
+ grid.queueGridRefresh();
+ }
+ }
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name expandRowChildren
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Expands this specific row, showing all children.
+ *
+ * @param {Grid} grid grid object
+ * @param {GridRow} row the row we want to expand
+ */
+ expandRowChildren: function ( grid, row ){
+ if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){
+ return;
+ }
+
+ service.setAllNodes(grid, row.treeNode, uiGridTreeBaseConstants.EXPANDED);
+ grid.treeBase.expandAll = service.allExpanded(grid.treeBase.tree);
+ grid.queueGridRefresh();
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name collapseRow
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Collapses this specific row
+ *
+ * @param {Grid} grid grid object
+ * @param {GridRow} row the row we want to collapse
+ */
+ collapseRow: function( grid, row ){
+ if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){
+ return;
+ }
+
+ if ( row.treeNode.state !== uiGridTreeBaseConstants.COLLAPSED ){
+ row.treeNode.state = uiGridTreeBaseConstants.COLLAPSED;
+ grid.treeBase.expandAll = false;
+ grid.api.treeBase.raise.rowCollapsed(row);
+ grid.queueGridRefresh();
+ }
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name collapseRowChildren
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Collapses this specific row and all children
+ *
+ * @param {Grid} grid grid object
+ * @param {GridRow} row the row we want to collapse
+ */
+ collapseRowChildren: function( grid, row ){
+ if ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ){
+ return;
+ }
+
+ service.setAllNodes(grid, row.treeNode, uiGridTreeBaseConstants.COLLAPSED);
+ grid.treeBase.expandAll = false;
+ grid.queueGridRefresh();
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name allExpanded
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Returns true if all rows are expanded, false
+ * if they're not. Walks the tree to determine this. Used
+ * to set the expandAll state.
+ *
+ * If the node has no children, then return true (it's immaterial
+ * whether it is expanded). If the node has children, then return
+ * false if this node is collapsed, or if any child node is not all expanded
+ *
+ * @param {object} tree the grid to check
+ * @returns {boolean} whether or not the tree is all expanded
+ */
+ allExpanded: function( tree ){
+ var allExpanded = true;
+ tree.forEach( function( node ){
+ if ( !service.allExpandedInternal( node ) ){
+ allExpanded = false;
+ }
+ });
+ return allExpanded;
+ },
+
+ allExpandedInternal: function( treeNode ){
+ if ( treeNode.children && treeNode.children.length > 0 ){
+ if ( treeNode.state === uiGridTreeBaseConstants.COLLAPSED ){
+ return false;
+ }
+ var allExpanded = true;
+ treeNode.children.forEach( function( node ){
+ if ( !service.allExpandedInternal( node ) ){
+ allExpanded = false;
+ }
+ });
+ return allExpanded;
+ } else {
+ return true;
+ }
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name treeRows
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description The rowProcessor that adds the nodes to the tree, and sets the visible
+ * state of each row based on it's parent state
+ *
+ * Assumes it is always called after the sorting processor, and the grouping processor if there is one.
+ * Performs any tree sorts itself after having built the tree
+ *
+ * Processes all the rows in order, setting the group level based on the $$treeLevel in the associated
+ * entity, and setting the visible state based on the parent's state.
+ *
+ * Calculates the deepest level of tree whilst it goes, and updates that so that the header column can be correctly
+ * sized.
+ *
+ * Aggregates if necessary along the way.
+ *
+ * @param {array} renderableRows the rows we want to process, usually the output from the previous rowProcessor
+ * @returns {array} the updated rows
+ */
+ treeRows: function( renderableRows ) {
+ var grid = this;
+
+ if (renderableRows.length === 0) {
+ service.updateRowHeaderWidth( grid );
+ return renderableRows;
+ }
+
+ grid.treeBase.tree = service.createTree( grid, renderableRows );
+ service.updateRowHeaderWidth( grid );
+
+ service.sortTree( grid );
+ service.fixFilter( grid );
+
+ return service.renderTree( grid.treeBase.tree );
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name createOrUpdateRowHeaderWidth
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Calculates the rowHeader width.
+ *
+ * If rowHeader is always present, updates the width.
+ *
+ * If rowHeader is only sometimes present (`treeRowHeaderAlwaysVisible: false`), determines whether there
+ * should be one, then creates or removes it as appropriate, with the created rowHeader having the
+ * right width.
+ *
+ * If there's never a rowHeader then never creates one: `showTreeRowHeader: false`
+ *
+ * @param {Grid} grid the grid we want to set the row header on
+ */
+ updateRowHeaderWidth: function( grid ){
+ var rowHeader = grid.getColumn(uiGridTreeBaseConstants.rowHeaderColName);
+
+ var newWidth = grid.options.treeRowHeaderBaseWidth + grid.options.treeIndent * Math.max(grid.treeBase.numberLevels - 1, 0);
+ if ( rowHeader && newWidth !== rowHeader.width ){
+ rowHeader.width = newWidth;
+ grid.queueRefresh();
+ }
+
+ var newVisibility = true;
+ if ( grid.options.showTreeRowHeader === false ){
+ newVisibility = false;
+ }
+ if ( grid.options.treeRowHeaderAlwaysVisible === false && grid.treeBase.numberLevels <= 0 ){
+ newVisibility = false;
+ }
+ if ( rowHeader && rowHeader.visible !== newVisibility ) {
+ rowHeader.visible = newVisibility;
+ rowHeader.colDef.visible = newVisibility;
+ grid.queueGridRefresh();
+ }
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name renderTree
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Creates an array of rows based on the tree, exporting only
+ * the visible nodes and leaves
+ *
+ * @param {array} nodeList The list of nodes - can be grid.treeBase.tree, or can be node.children when
+ * we're calling recursively
+ * @returns {array} renderable rows
+ */
+ renderTree: function( nodeList ){
+ var renderableRows = [];
+
+ nodeList.forEach( function ( node ){
+ if ( node.row.visible ){
+ renderableRows.push( node.row );
+ }
+ if ( node.state === uiGridTreeBaseConstants.EXPANDED && node.children && node.children.length > 0 ){
+ renderableRows = renderableRows.concat( service.renderTree( node.children ) );
+ }
+ });
+ return renderableRows;
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name createTree
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Creates a tree from the renderableRows
+ *
+ * @param {Grid} grid The grid
+ * @param {array} renderableRows The rows we want to create a tree from
+ * @returns {object} The tree we've build
+ */
+ createTree: function( grid, renderableRows ) {
+ var currentLevel = -1;
+ var parents = [];
+ var currentState;
+ grid.treeBase.tree = [];
+ grid.treeBase.numberLevels = 0;
+ var aggregations = service.getAggregations( grid );
+
+ var createNode = function( row ){
+ if ( typeof(row.entity.$$treeLevel) !== 'undefined' && row.treeLevel !== row.entity.$$treeLevel ){
+ row.treeLevel = row.entity.$$treeLevel;
+ }
+
+ if ( row.treeLevel <= currentLevel ){
+ // pop any levels that aren't parents of this level, formatting the aggregation at the same time
+ while ( row.treeLevel <= currentLevel ){
+ var lastParent = parents.pop();
+ service.finaliseAggregations( lastParent );
+ currentLevel--;
+ }
+
+ // reset our current state based on the new parent, set to expanded if this is a level 0 node
+ if ( parents.length > 0 ){
+ currentState = service.setCurrentState(parents);
+ } else {
+ currentState = uiGridTreeBaseConstants.EXPANDED;
+ }
+ }
+
+ // aggregate if this is a leaf node
+ if ( ( typeof(row.treeLevel) === 'undefined' || row.treeLevel === null || row.treeLevel < 0 ) && row.visible ){
+ service.aggregate( grid, row, parents );
+ }
+
+ // add this node to the tree
+ service.addOrUseNode(grid, row, parents, aggregations);
+
+ if ( typeof(row.treeLevel) !== 'undefined' && row.treeLevel !== null && row.treeLevel >= 0 ){
+ parents.push(row);
+ currentLevel++;
+ currentState = service.setCurrentState(parents);
+ }
+
+ // update the tree number of levels, so we can set header width if we need to
+ if ( grid.treeBase.numberLevels < row.treeLevel + 1){
+ grid.treeBase.numberLevels = row.treeLevel + 1;
+ }
+ };
+
+ renderableRows.forEach( createNode );
+
+ // finalise remaining aggregations
+ while ( parents.length > 0 ){
+ var lastParent = parents.pop();
+ service.finaliseAggregations( lastParent );
+ }
+
+ return grid.treeBase.tree;
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name addOrUseNode
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Creates a tree node for this row. If this row already has a treeNode
+ * recorded against it, preserves the state, but otherwise overwrites the data.
+ *
+ * @param {grid} grid The grid we're operating on
+ * @param {gridRow} row The row we want to set
+ * @param {array} parents An array of the parents this row should have
+ * @param {array} aggregationBase Empty aggregation information
+ * @returns {undefined} Updates the parents array, updates the row to have a treeNode, and updates the
+ * grid.treeBase.tree
+ */
+ addOrUseNode: function( grid, row, parents, aggregationBase ){
+ var newAggregations = [];
+ aggregationBase.forEach( function(aggregation){
+ newAggregations.push(service.buildAggregationObject(aggregation.col));
+ });
+
+ var newNode = { state: uiGridTreeBaseConstants.COLLAPSED, row: row, parentRow: null, aggregations: newAggregations, children: [] };
+ if ( row.treeNode ){
+ newNode.state = row.treeNode.state;
+ }
+ if ( parents.length > 0 ){
+ newNode.parentRow = parents[parents.length - 1];
+ }
+ row.treeNode = newNode;
+
+ if ( parents.length === 0 ){
+ grid.treeBase.tree.push( newNode );
+ } else {
+ parents[parents.length - 1].treeNode.children.push( newNode );
+ }
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name setCurrentState
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Looks at the parents array to determine our current state.
+ * If any node in the hierarchy is collapsed, then return collapsed, otherwise return
+ * expanded.
+ *
+ * @param {array} parents An array of the parents this row should have
+ * @returns {string} The state we should be setting to any nodes we see
+ */
+ setCurrentState: function( parents ){
+ var currentState = uiGridTreeBaseConstants.EXPANDED;
+ parents.forEach( function(parent){
+ if ( parent.treeNode.state === uiGridTreeBaseConstants.COLLAPSED ){
+ currentState = uiGridTreeBaseConstants.COLLAPSED;
+ }
+ });
+ return currentState;
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name sortTree
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Performs a recursive sort on the tree nodes, sorting the
+ * children of each node and putting them back into the children array.
+ *
+ * Before doing this it turns back on all the sortIgnore - things that were previously
+ * ignored we process now. Since we're sorting within the nodes, presumably anything
+ * that was already sorted is how we derived the nodes, we can keep those sorts too.
+ *
+ * We only sort tree nodes that are expanded - no point in wasting effort sorting collapsed
+ * nodes
+ *
+ * @param {Grid} grid The grid to get the aggregation information from
+ * @returns {array} The aggregation information
+ */
+ sortTree: function( grid ){
+ grid.columns.forEach( function( column ) {
+ if ( column.sort && column.sort.ignoreSort ){
+ delete column.sort.ignoreSort;
+ }
+ });
+
+ grid.treeBase.tree = service.sortInternal( grid, grid.treeBase.tree );
+ },
+
+ sortInternal: function( grid, treeList ){
+ var rows = treeList.map( function( node ){
+ return node.row;
+ });
+
+ rows = rowSorter.sort( grid, rows, grid.columns );
+
+ var treeNodes = rows.map( function( row ){
+ return row.treeNode;
+ });
+
+ treeNodes.forEach( function( node ){
+ if ( node.state === uiGridTreeBaseConstants.EXPANDED && node.children && node.children.length > 0 ){
+ node.children = service.sortInternal( grid, node.children );
+ }
+ });
+
+ return treeNodes;
+ },
+
+ /**
+ * @ngdoc function
+ * @name fixFilter
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description After filtering has run, we need to go back through the tree
+ * and make sure the parent rows are always visible if any of the child rows
+ * are visible (filtering may make a child visible, but the parent may not
+ * match the filter criteria)
+ *
+ * This has a risk of being computationally expensive, we do it by walking
+ * the tree and remembering whether there are any invisible nodes on the
+ * way down.
+ *
+ * @param {Grid} grid the grid to fix filters on
+ */
+ fixFilter: function( grid ){
+ var parentsVisible;
+
+ grid.treeBase.tree.forEach( function( node ){
+ if ( node.children && node.children.length > 0 ){
+ parentsVisible = node.row.visible;
+ service.fixFilterInternal( node.children, parentsVisible );
+ }
+ });
+ },
+
+ fixFilterInternal: function( nodes, parentsVisible) {
+ nodes.forEach( function( node ){
+ if ( node.row.visible && !parentsVisible ){
+ service.setParentsVisible( node );
+ parentsVisible = true;
+ }
+
+ if ( node.children && node.children.length > 0 ){
+ if ( service.fixFilterInternal( node.children, ( parentsVisible && node.row.visible ) ) ) {
+ parentsVisible = true;
+ }
+ }
+ });
+
+ return parentsVisible;
+ },
+
+ setParentsVisible: function( node ){
+ while ( node.parentRow ){
+ node.parentRow.visible = true;
+ node = node.parentRow.treeNode;
+ }
+ },
+
+ /**
+ * @ngdoc function
+ * @name buildAggregationObject
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Build the object which is stored on the column for holding meta-data about the aggregation.
+ * This method should only be called with columns which have an aggregation.
+ *
+ * @param {GridColumn} column The column which this object relates to
+ * @returns {object} {col: GridColumn object, label: string, type: string (optional)}
+ */
+ buildAggregationObject: function( column ){
+ var newAggregation = { col: column };
+
+ if ( column.treeAggregation && column.treeAggregation.type ){
+ newAggregation.type = column.treeAggregation.type;
+ }
+
+ if ( column.treeAggregation && column.treeAggregation.label ){
+ newAggregation.label = column.treeAggregation.label;
+ }
+
+ return newAggregation;
+ },
+
+ /**
+ * @ngdoc function
+ * @name getAggregations
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Looks through the grid columns to find those with aggregations,
+ * and collates the aggregation information into an array, returns that array
+ *
+ * @param {Grid} grid the grid to get the aggregation information from
+ * @returns {array} the aggregation information
+ */
+ getAggregations: function( grid ){
+ var aggregateArray = [];
+
+ grid.columns.forEach( function(column){
+ if ( typeof(column.treeAggregationFn) !== 'undefined' ){
+ aggregateArray.push( service.buildAggregationObject(column) );
+
+ if ( grid.options.showColumnFooter && typeof(column.colDef.aggregationType) === 'undefined' && column.treeAggregation ){
+ // Add aggregation object for footer
+ column.treeFooterAggregation = service.buildAggregationObject(column);
+ column.aggregationType = service.treeFooterAggregationType;
+ }
+ }
+ });
+ return aggregateArray;
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name aggregate
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Accumulate the data from this row onto the aggregations for each parent
+ *
+ * Iterate over the parents, then iterate over the aggregations for each of those parents,
+ * and perform the aggregation for each individual aggregation
+ *
+ * @param {Grid} grid grid object
+ * @param {GridRow} row the row we want to set grouping visibility on
+ * @param {array} parents the parents that we would want to aggregate onto
+ */
+ aggregate: function( grid, row, parents ){
+ if ( parents.length === 0 && row.treeNode && row.treeNode.aggregations ){
+ row.treeNode.aggregations.forEach(function(aggregation){
+ // Calculate aggregations for footer even if there are no grouped rows
+ if ( typeof(aggregation.col.treeFooterAggregation) !== 'undefined' ) {
+ var fieldValue = grid.getCellValue(row, aggregation.col);
+ var numValue = Number(fieldValue);
+ aggregation.col.treeAggregationFn(aggregation.col.treeFooterAggregation, fieldValue, numValue, row);
+ }
+ });
+ }
+
+ parents.forEach( function( parent, index ){
+ if ( parent.treeNode.aggregations ){
+ parent.treeNode.aggregations.forEach( function( aggregation ){
+ var fieldValue = grid.getCellValue(row, aggregation.col);
+ var numValue = Number(fieldValue);
+ aggregation.col.treeAggregationFn(aggregation, fieldValue, numValue, row);
+
+ if ( index === 0 && typeof(aggregation.col.treeFooterAggregation) !== 'undefined' ){
+ aggregation.col.treeAggregationFn(aggregation.col.treeFooterAggregation, fieldValue, numValue, row);
+ }
+ });
+ }
+ });
+ },
+
+
+ // Aggregation routines - no doco needed as self evident
+ nativeAggregations: function() {
+ var nativeAggregations = {
+ count: {
+ label: i18nService.get().aggregation.count,
+ menuTitle: i18nService.get().grouping.aggregate_count,
+ aggregationFn: function (aggregation, fieldValue, numValue) {
+ if (typeof(aggregation.value) === 'undefined') {
+ aggregation.value = 1;
+ } else {
+ aggregation.value++;
+ }
+ }
+ },
+
+ sum: {
+ label: i18nService.get().aggregation.sum,
+ menuTitle: i18nService.get().grouping.aggregate_sum,
+ aggregationFn: function( aggregation, fieldValue, numValue ) {
+ if (!isNaN(numValue)) {
+ if (typeof(aggregation.value) === 'undefined') {
+ aggregation.value = numValue;
+ } else {
+ aggregation.value += numValue;
+ }
+ }
+ }
+ },
+
+ min: {
+ label: i18nService.get().aggregation.min,
+ menuTitle: i18nService.get().grouping.aggregate_min,
+ aggregationFn: function( aggregation, fieldValue, numValue ) {
+ if (typeof(aggregation.value) === 'undefined') {
+ aggregation.value = fieldValue;
+ } else {
+ if (typeof(fieldValue) !== 'undefined' && fieldValue !== null && (fieldValue < aggregation.value || aggregation.value === null)) {
+ aggregation.value = fieldValue;
+ }
+ }
+ }
+ },
+
+ max: {
+ label: i18nService.get().aggregation.max,
+ menuTitle: i18nService.get().grouping.aggregate_max,
+ aggregationFn: function( aggregation, fieldValue, numValue ){
+ if ( typeof(aggregation.value) === 'undefined' ){
+ aggregation.value = fieldValue;
+ } else {
+ if ( typeof(fieldValue) !== 'undefined' && fieldValue !== null && (fieldValue > aggregation.value || aggregation.value === null)){
+ aggregation.value = fieldValue;
+ }
+ }
+ }
+ },
+
+ avg: {
+ label: i18nService.get().aggregation.avg,
+ menuTitle: i18nService.get().grouping.aggregate_avg,
+ aggregationFn: function( aggregation, fieldValue, numValue ){
+ if ( typeof(aggregation.count) === 'undefined' ){
+ aggregation.count = 1;
+ } else {
+ aggregation.count++;
+ }
+
+ if ( isNaN(numValue) ){
+ return;
+ }
+
+ if ( typeof(aggregation.value) === 'undefined' || typeof(aggregation.sum) === 'undefined' ){
+ aggregation.value = numValue;
+ aggregation.sum = numValue;
+ } else {
+ aggregation.sum += numValue;
+ aggregation.value = aggregation.sum / aggregation.count;
+ }
+ }
+ }
+ };
+ return nativeAggregations;
+ },
+
+ /**
+ * @ngdoc function
+ * @name finaliseAggregation
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Helper function used to finalize aggregation nodes and footer cells
+ *
+ * @param {gridRow} row The parent we're finalising
+ * @param {aggregation} aggregation The aggregation object manipulated by the aggregationFn
+ */
+ finaliseAggregation: function(row, aggregation){
+ if ( aggregation.col.treeAggregationUpdateEntity && typeof(row) !== 'undefined' && typeof(row.entity[ '$$' + aggregation.col.uid ]) !== 'undefined' ){
+ angular.extend( aggregation, row.entity[ '$$' + aggregation.col.uid ]);
+ }
+
+ if ( typeof(aggregation.col.treeAggregationFinalizerFn) === 'function' ){
+ aggregation.col.treeAggregationFinalizerFn( aggregation );
+ }
+ if ( typeof(aggregation.col.customTreeAggregationFinalizerFn) === 'function' ){
+ aggregation.col.customTreeAggregationFinalizerFn( aggregation );
+ }
+ if ( typeof(aggregation.rendered) === 'undefined' ){
+ aggregation.rendered = aggregation.label ? aggregation.label + aggregation.value : aggregation.value;
+ }
+ },
+
+ /**
+ * @ngdoc function
+ * @name finaliseAggregations
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Format the data from the aggregation into the rendered text
+ * e.g. if we had label: 'sum: ' and value: 25, we'd create 'sum: 25'.
+ *
+ * As part of this we call any formatting callback routines we've been provided.
+ *
+ * We write our aggregation out to the row.entity if treeAggregationUpdateEntity is
+ * set on the column - we don't overwrite any information that's already there, we append
+ * to it so that grouping can have set the groupVal beforehand without us overwriting it.
+ *
+ * We need to copy the data from the row.entity first before we finalise the aggregation,
+ * we need that information for the finaliserFn
+ *
+ * @param {gridRow} row the parent we're finalising
+ */
+ finaliseAggregations: function( row ){
+ if ( row == null || typeof(row.treeNode.aggregations) === 'undefined' ){
+ return;
+ }
+
+ row.treeNode.aggregations.forEach( function( aggregation ) {
+ service.finaliseAggregation(row, aggregation);
+
+ if ( aggregation.col.treeAggregationUpdateEntity ){
+ var aggregationCopy = {};
+ angular.forEach( aggregation, function( value, key ){
+ if ( aggregation.hasOwnProperty(key) && key !== 'col' ){
+ aggregationCopy[key] = value;
+ }
+ });
+
+ row.entity[ '$$' + aggregation.col.uid ] = aggregationCopy;
+ }
+ });
+ },
+
+ /**
+ * @ngdoc function
+ * @name treeFooterAggregationType
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Uses the tree aggregation functions and finalizers to set the
+ * column footer aggregations.
+ *
+ * @param {rows} rows The visible rows. not used, but accepted to match signature of GridColumn.aggregationType
+ * @param {GridColumn} column The column we are finalizing
+ */
+ treeFooterAggregationType: function( rows, column ) {
+ service.finaliseAggregation(undefined, column.treeFooterAggregation);
+ if ( typeof(column.treeFooterAggregation.value) === 'undefined' || column.treeFooterAggregation.rendered === null ){
+ // The was apparently no aggregation performed (perhaps this is a grouped column
+ return '';
+ }
+ return column.treeFooterAggregation.rendered;
+ }
+ };
+
+ return service;
+
+ }]);
+
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.treeBase.directive:uiGridTreeRowHeaderButtons
+ * @element div
+ *
+ * @description Provides the expand/collapse button on rows
+ */
+ module.directive('uiGridTreeBaseRowHeaderButtons', ['$templateCache', 'uiGridTreeBaseService',
+ function ($templateCache, uiGridTreeBaseService) {
+ return {
+ replace: true,
+ restrict: 'E',
+ template: $templateCache.get('ui-grid/treeBaseRowHeaderButtons'),
+ scope: true,
+ require: '^uiGrid',
+ link: function($scope, $elm, $attrs, uiGridCtrl) {
+ var self = uiGridCtrl.grid;
+ $scope.treeButtonClass = function(row) {
+ if ( ( self.options.showTreeExpandNoChildren && row.treeLevel > -1 ) || ( row.treeNode.children && row.treeNode.children.length > 0 ) ) {
+ if (row.treeNode.state === 'expanded' ) {
+ return 'ui-grid-icon-minus-squared';
+ }
+ if (row.treeNode.state === 'collapsed' ) {
+ return 'ui-grid-icon-plus-squared';
+ }
+ }
+ };
+ $scope.treeButtonClick = function(row, evt) {
+ evt.stopPropagation();
+ uiGridTreeBaseService.toggleRowTreeState(self, row, evt);
+ };
+ }
+ };
+ }]);
+
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.treeBase.directive:uiGridTreeBaseExpandAllButtons
+ * @element div
+ *
+ * @description Provides the expand/collapse all button
+ */
+ module.directive('uiGridTreeBaseExpandAllButtons', ['$templateCache', 'uiGridTreeBaseService',
+ function ($templateCache, uiGridTreeBaseService) {
+ return {
+ replace: true,
+ restrict: 'E',
+ template: $templateCache.get('ui-grid/treeBaseExpandAllButtons'),
+ scope: false,
+ link: function($scope, $elm, $attrs, uiGridCtrl) {
+ var self = $scope.col.grid;
+ $scope.headerButtonClass = function() {
+ if (self.treeBase.numberLevels > 0 && self.treeBase.expandAll) {
+ return 'ui-grid-icon-minus-squared';
+ }
+ if (self.treeBase.numberLevels > 0 && !self.treeBase.expandAll) {
+ return 'ui-grid-icon-plus-squared';
+ }
+ };
+ $scope.headerButtonClick = function(row, evt) {
+ if ( self.treeBase.expandAll ){
+ uiGridTreeBaseService.collapseAllRows(self, evt);
+ } else {
+ uiGridTreeBaseService.expandAllRows(self, evt);
+ }
+ };
+ }
+ };
+ }]);
+
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.treeBase.directive:uiGridViewport
+ * @element div
+ *
+ * @description Stacks on top of ui.grid.uiGridViewport to set formatting on a tree header row
+ */
+ module.directive('uiGridViewport',
+ ['$compile', 'uiGridConstants', 'gridUtil', '$parse',
+ function ($compile, uiGridConstants, gridUtil, $parse) {
+ return {
+ priority: -200, // run after default directive
+ scope: false,
+ compile: function ($elm, $attrs) {
+ var rowRepeatDiv = angular.element($elm.children().children()[0]);
+
+ var existingNgClass = rowRepeatDiv.attr("ng-class");
+ var newNgClass = '';
+ if ( existingNgClass ) {
+ newNgClass = existingNgClass.slice(0, -1) + ",'ui-grid-tree-header-row': row.treeLevel > -1}";
+ } else {
+ newNgClass = "{'ui-grid-tree-header-row': row.treeLevel > -1}";
+ }
+ rowRepeatDiv.attr("ng-class", newNgClass);
+
+ return {
+ pre: function ($scope, $elm, $attrs, controllers) {
+
+ },
+ post: function ($scope, $elm, $attrs, controllers) {
+ }
+ };
+ }
+ };
+ }]);
+})();
diff --git a/release/4.4.11/ui-grid.tree-base.min.js b/release/4.4.11/ui-grid.tree-base.min.js
new file mode 100644
index 000000000..bb41e74ec
--- /dev/null
+++ b/release/4.4.11/ui-grid.tree-base.min.js
@@ -0,0 +1,7 @@
+/*!
+ * ui-grid - v4.4.11 - 2018-05-16
+ * Copyright (c) 2018 ; License: MIT
+ */
+
+
+!function(){"use strict";var e=angular.module("ui.grid.treeBase",["ui.grid"]);e.constant("uiGridTreeBaseConstants",{featureName:"treeBase",rowHeaderColName:"treeBaseRowHeaderCol",EXPANDED:"expanded",COLLAPSED:"collapsed",aggregation:{COUNT:"count",SUM:"sum",MAX:"max",MIN:"min",AVG:"avg"}}),e.service("uiGridTreeBaseService",["$q","uiGridTreeBaseConstants","gridUtil","GridRow","gridClassFactory","i18nService","uiGridConstants","rowSorter",function(e,i,t,r,n,o,a,l){var g={initializeGrid:function(r,e){r.treeBase={},r.treeBase.numberLevels=0,r.treeBase.expandAll=!1,r.treeBase.tree=[],g.defaultGridOptions(r.options),r.registerRowsProcessor(g.treeRows,410),r.registerColumnBuilder(g.treeBaseColumnBuilder),g.createRowHeader(r);var t={events:{treeBase:{rowExpanded:{},rowCollapsed:{}}},methods:{treeBase:{expandAllRows:function(){g.expandAllRows(r)},collapseAllRows:function(){g.collapseAllRows(r)},toggleRowTreeState:function(e){g.toggleRowTreeState(r,e)},expandRow:function(e,t){g.expandRow(r,e,t)},expandRowChildren:function(e){g.expandRowChildren(r,e)},collapseRow:function(e){g.collapseRow(r,e)},collapseRowChildren:function(e){g.collapseRowChildren(r,e)},getTreeExpandedState:function(){return{expandedState:g.getTreeState(r)}},setTreeState:function(e){g.setTreeState(r,e)},getRowChildren:function(e){return e.treeNode.children.map(function(e){return e.row})}}}};r.api.registerEventsFromObject(t.events),r.api.registerMethodsFromObject(t.methods)},defaultGridOptions:function(e){e.treeRowHeaderBaseWidth=e.treeRowHeaderBaseWidth||30,e.treeIndent=null!=e.treeIndent?e.treeIndent:10,e.showTreeRowHeader=!1!==e.showTreeRowHeader,e.showTreeExpandNoChildren=!1!==e.showTreeExpandNoChildren,e.treeRowHeaderAlwaysVisible=!1!==e.treeRowHeaderAlwaysVisible,e.treeCustomAggregations=e.treeCustomAggregations||{},e.enableExpandAll=!1!==e.enableExpandAll},treeBaseColumnBuilder:function(e,t,r){void 0!==e.customTreeAggregationFn&&(t.treeAggregationFn=e.customTreeAggregationFn),void 0!==e.treeAggregationType&&(t.treeAggregation={type:e.treeAggregationType},void 0!==r.treeCustomAggregations[e.treeAggregationType]?(t.treeAggregationFn=r.treeCustomAggregations[e.treeAggregationType].aggregationFn,t.treeAggregationFinalizerFn=r.treeCustomAggregations[e.treeAggregationType].finalizerFn,t.treeAggregation.label=r.treeCustomAggregations[e.treeAggregationType].label):void 0!==g.nativeAggregations()[e.treeAggregationType]&&(t.treeAggregationFn=g.nativeAggregations()[e.treeAggregationType].aggregationFn,t.treeAggregation.label=g.nativeAggregations()[e.treeAggregationType].label)),void 0!==e.treeAggregationLabel&&(void 0===t.treeAggregation&&(t.treeAggregation={}),t.treeAggregation.label=e.treeAggregationLabel),t.treeAggregationUpdateEntity=!1!==e.treeAggregationUpdateEntity,void 0===t.customTreeAggregationFinalizerFn&&(t.customTreeAggregationFinalizerFn=e.customTreeAggregationFinalizerFn)},createRowHeader:function(e){var t={name:i.rowHeaderColName,displayName:"",width:e.options.treeRowHeaderBaseWidth,minWidth:10,cellTemplate:"ui-grid/treeBaseRowHeader",headerCellTemplate:"ui-grid/treeBaseHeaderCell",enableColumnResizing:!1,enableColumnMenu:!1,exporterSuppressExport:!0,allowCellFocus:!0};t.visible=e.options.treeRowHeaderAlwaysVisible,e.addRowHeaderColumn(t,-100)},expandAllRows:function(t){t.treeBase.tree.forEach(function(e){g.setAllNodes(t,e,i.EXPANDED)}),t.treeBase.expandAll=!0,t.queueGridRefresh()},collapseAllRows:function(t){t.treeBase.tree.forEach(function(e){g.setAllNodes(t,e,i.COLLAPSED)}),t.treeBase.expandAll=!1,t.queueGridRefresh()},setAllNodes:function(t,e,r){void 0!==e.state&&e.state!==r&&((e.state=r)===i.EXPANDED?t.api.treeBase.raise.rowExpanded(e.row):t.api.treeBase.raise.rowCollapsed(e.row)),e.children&&e.children.forEach(function(e){g.setAllNodes(t,e,r)})},toggleRowTreeState:function(e,t){void 0===t.treeLevel||null===t.treeLevel||t.treeLevel<0||(t.treeNode.state===i.EXPANDED?g.collapseRow(e,t):g.expandRow(e,t,!1),e.queueGridRefresh())},expandRow:function(e,t,r){if(r){for(var n=[];t&&void 0!==t.treeLevel&&null!==t.treeLevel&&0<=t.treeLevel&&t.treeNode.state!==i.EXPANDED;)n.push(t),t=t.treeNode.parentRow;if(0
+ *
+ *
+ *
+ */
+
+ var module = angular.module('ui.grid.treeView', ['ui.grid', 'ui.grid.treeBase']);
+
+ /**
+ * @ngdoc object
+ * @name ui.grid.treeView.constant:uiGridTreeViewConstants
+ *
+ * @description constants available in treeView module, this includes
+ * all the constants declared in the treeBase module (these are manually copied
+ * as there isn't an easy way to include constants in another constants file, and
+ * we don't want to make users include treeBase)
+ *
+ */
+ module.constant('uiGridTreeViewConstants', {
+ featureName: "treeView",
+ rowHeaderColName: 'treeBaseRowHeaderCol',
+ EXPANDED: 'expanded',
+ COLLAPSED: 'collapsed',
+ aggregation: {
+ COUNT: 'count',
+ SUM: 'sum',
+ MAX: 'max',
+ MIN: 'min',
+ AVG: 'avg'
+ }
+ });
+
+ /**
+ * @ngdoc service
+ * @name ui.grid.treeView.service:uiGridTreeViewService
+ *
+ * @description Services for treeView features
+ */
+ module.service('uiGridTreeViewService', ['$q', 'uiGridTreeViewConstants', 'uiGridTreeBaseConstants', 'uiGridTreeBaseService', 'gridUtil', 'GridRow', 'gridClassFactory', 'i18nService', 'uiGridConstants',
+ function ($q, uiGridTreeViewConstants, uiGridTreeBaseConstants, uiGridTreeBaseService, gridUtil, GridRow, gridClassFactory, i18nService, uiGridConstants) {
+
+ var service = {
+
+ initializeGrid: function (grid, $scope) {
+ uiGridTreeBaseService.initializeGrid( grid, $scope );
+
+ /**
+ * @ngdoc object
+ * @name ui.grid.treeView.grid:treeView
+ *
+ * @description Grid properties and functions added for treeView
+ */
+ grid.treeView = {};
+
+ grid.registerRowsProcessor(service.adjustSorting, 60);
+
+ /**
+ * @ngdoc object
+ * @name ui.grid.treeView.api:PublicApi
+ *
+ * @description Public Api for treeView feature
+ */
+ var publicApi = {
+ events: {
+ treeView: {
+ }
+ },
+ methods: {
+ treeView: {
+ }
+ }
+ };
+
+ grid.api.registerEventsFromObject(publicApi.events);
+
+ grid.api.registerMethodsFromObject(publicApi.methods);
+
+ },
+
+ defaultGridOptions: function (gridOptions) {
+ //default option to true unless it was explicitly set to false
+ /**
+ * @ngdoc object
+ * @name ui.grid.treeView.api:GridOptions
+ *
+ * @description GridOptions for treeView feature, these are available to be
+ * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
+ *
+ * Many tree options are set on treeBase, make sure to look at that feature in
+ * conjunction with these options.
+ */
+
+ /**
+ * @ngdoc object
+ * @name enableTreeView
+ * @propertyOf ui.grid.treeView.api:GridOptions
+ * @description Enable row tree view for entire grid.
+ *
Defaults to true
+ */
+ gridOptions.enableTreeView = gridOptions.enableTreeView !== false;
+
+ },
+
+
+ /**
+ * @ngdoc function
+ * @name adjustSorting
+ * @methodOf ui.grid.treeBase.service:uiGridTreeBaseService
+ * @description Trees cannot be sorted the same as flat lists of rows -
+ * trees are sorted recursively within each level - so the children of each
+ * node are sorted, but not the full set of rows.
+ *
+ * To achieve this, we suppress the normal sorting by setting ignoreSort on
+ * each of the sort columns. When the treeBase rowsProcessor runs it will then
+ * unignore these, and will perform a recursive sort against the tree that it builds.
+ *
+ * @param {array} renderableRows the rows that we need to pass on through
+ * @returns {array} renderableRows that we passed on through
+ */
+ adjustSorting: function( renderableRows ) {
+ var grid = this;
+
+ grid.columns.forEach( function( column ){
+ if ( column.sort ){
+ column.sort.ignoreSort = true;
+ }
+ });
+
+ return renderableRows;
+ }
+
+ };
+
+ return service;
+
+ }]);
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.treeView.directive:uiGridTreeView
+ * @element div
+ * @restrict A
+ *
+ * @description Adds treeView features to grid
+ *
+ * @example
+
+ *
+ *
+ *
+ */
+
+ var module = angular.module('ui.grid.validate', ['ui.grid']);
+
+
+ /**
+ * @ngdoc service
+ * @name ui.grid.validate.service:uiGridValidateService
+ *
+ * @description Services for validation features
+ */
+ module.service('uiGridValidateService', ['$sce', '$q', '$http', 'i18nService', 'uiGridConstants', function ($sce, $q, $http, i18nService, uiGridConstants) {
+
+ var service = {
+
+ /**
+ * @ngdoc object
+ * @name validatorFactories
+ * @propertyOf ui.grid.validate.service:uiGridValidateService
+ * @description object containing all the factories used to validate data.
+ * These factories will be in the form
+ * ```
+ * {
+ * validatorFactory: function(argument) {
+ * return function(newValue, oldValue, rowEntity, colDef) {
+ * return true || false || promise
+ * }
+ * },
+ * messageFunction: function(argument) {
+ * return string
+ * }
+ * }
+ * ```
+ *
+ * Promises should return true or false as result according to the result of validation.
+ */
+ validatorFactories: {},
+
+
+ /**
+ * @ngdoc service
+ * @name setExternalFactoryFunction
+ * @methodOf ui.grid.validate.service:uiGridValidateService
+ * @description Adds a way to retrieve validators from an external service
+ *
";
+ });
+
+ return $sce.trustAsHtml('
+ * gridApi.validate.on.validationFailed(scope, function(rowEntity, colDef, newValue, oldValue){...})
+ *
+ * @param {object} rowEntity the options.data element whose validation failed
+ * @param {object} colDef the column whose validation failed
+ * @param {object} newValue new value
+ * @param {object} oldValue old value
+ */
+ validationFailed: function (rowEntity, colDef, newValue, oldValue) {
+ }
+ }
+ },
+ methods: {
+ validate: {
+ /**
+ * @ngdoc function
+ * @name isInvalid
+ * @methodOf ui.grid.validate.api:PublicApi
+ * @description checks if a cell (identified by rowEntity, colDef) is invalid
+ * @param {object} rowEntity gridOptions.data[] array instance we want to check
+ * @param {object} colDef the column whose errors we want to check
+ * @returns {boolean} true if the cell value is not valid
+ */
+ isInvalid: function(rowEntity, colDef) {
+ return grid.validate.isInvalid(rowEntity, colDef);
+ },
+ /**
+ * @ngdoc function
+ * @name getErrorMessages
+ * @methodOf ui.grid.validate.api:PublicApi
+ * @description returns an array of i18n-ed error messages.
+ * @param {object} rowEntity gridOptions.data[] array instance whose errors we are looking for
+ * @param {object} colDef the column whose errors we are looking for
+ * @returns {array} An array of strings containing all the error messages for the cell
+ */
+ getErrorMessages: function (rowEntity, colDef) {
+ return grid.validate.getErrorMessages(rowEntity, colDef);
+ },
+ /**
+ * @ngdoc function
+ * @name getFormattedErrors
+ * @methodOf ui.grid.validate.api:PublicApi
+ * @description returns the error i18n-ed and formatted in html to be shown inside the page.
+ * @param {object} rowEntity gridOptions.data[] array instance whose errors we are looking for
+ * @param {object} colDef the column whose errors we are looking for
+ * @returns {object} An object that can be used in a template (like a cellTemplate) to display the
+ * message inside the page (i.e. inside a div)
+ */
+ getFormattedErrors: function (rowEntity, colDef) {
+ return grid.validate.getFormattedErrors(rowEntity, colDef);
+ },
+ /**
+ * @ngdoc function
+ * @name getTitleFormattedErrors
+ * @methodOf ui.grid.validate.api:PublicApi
+ * @description returns the error i18n-ed and formatted in javaScript to be shown inside an html
+ * title attribute.
+ * @param {object} rowEntity gridOptions.data[] array instance whose errors we are looking for
+ * @param {object} colDef the column whose errors we are looking for
+ * @returns {object} An object that can be used in a template (like a cellTemplate) to display the
+ * message inside an html title attribute
+ */
+ getTitleFormattedErrors: function (rowEntity, colDef) {
+ return grid.validate.getTitleFormattedErrors(rowEntity, colDef);
+ }
+ }
+ }
+ };
+
+ grid.api.registerEventsFromObject(publicApi.events);
+ grid.api.registerMethodsFromObject(publicApi.methods);
+
+ if (grid.edit) {
+ grid.api.edit.on.afterCellEdit(scope, function(rowEntity, colDef, newValue, oldValue) {
+ grid.validate.runValidators(rowEntity, colDef, newValue, oldValue, grid);
+ });
+ }
+
+ service.createDefaultValidators();
+ }
+
+ };
+
+ return service;
+ }]);
+
+
+ /**
+ * @ngdoc directive
+ * @name ui.grid.validate.directive:uiGridValidate
+ * @element div
+ * @restrict A
+ * @description Adds validating features to the ui-grid directive.
+ * @example
+
"}),n.trustAsHtml("
"}),n.trustAsHtml("