2 * Angular Material Design
3 * https://github.com/angular/material
7 goog.provide('ngmaterial.components.virtualRepeat');
8 goog.require('ngmaterial.components.showHide');
9 goog.require('ngmaterial.core');
12 * @name material.components.virtualRepeat
14 VirtualRepeatContainerController['$inject'] = ["$$rAF", "$mdUtil", "$mdConstant", "$parse", "$rootScope", "$window", "$scope", "$element", "$attrs"];
15 VirtualRepeatController['$inject'] = ["$scope", "$element", "$attrs", "$browser", "$document", "$rootScope", "$$rAF", "$mdUtil"];
16 VirtualRepeatDirective['$inject'] = ["$parse"];
17 angular.module('material.components.virtualRepeat', [
19 'material.components.showHide'
21 .directive('mdVirtualRepeatContainer', VirtualRepeatContainerDirective)
22 .directive('mdVirtualRepeat', VirtualRepeatDirective);
27 * @name mdVirtualRepeatContainer
28 * @module material.components.virtualRepeat
31 * `md-virtual-repeat-container` provides the scroll container for md-virtual-repeat.
33 * VirtualRepeat is a limited substitute for ng-repeat that renders only
34 * enough DOM nodes to fill the container and recycling them as the user scrolls.
36 * Once an element is not visible anymore, the VirtualRepeat recycles it and will reuse it for
37 * another visible item by replacing the previous dataset with the new one.
41 * - When having one-time bindings inside of the view template, the VirtualRepeat will not properly
42 * update the bindings for new items, since the view will be recycled.
44 * - Directives inside of a VirtualRepeat will be only compiled (linked) once, because those
45 * are will be recycled items and used for other items.
46 * The VirtualRepeat just updates the scope bindings.
51 * > The VirtualRepeat is a similar implementation to the Android
52 * [RecyclerView](https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html)
54 * <!-- This comment forces a break between blockquotes //-->
56 * > Please also review the <a ng-href="api/directive/mdVirtualRepeat">VirtualRepeat</a>
57 * documentation for more information.
63 * <md-virtual-repeat-container md-top-index="topIndex">
64 * <div md-virtual-repeat="i in items" md-item-size="20">Hello {{i}}!</div>
65 * </md-virtual-repeat-container>
68 * @param {number=} md-top-index Binds the index of the item that is at the top of the scroll
69 * container to $scope. It can both read and set the scroll position.
70 * @param {boolean=} md-orient-horizontal Whether the container should scroll horizontally
71 * (defaults to orientation and scrolling vertically).
72 * @param {boolean=} md-auto-shrink When present, the container will shrink to fit
73 * the number of items when that number is less than its original size.
74 * @param {number=} md-auto-shrink-min Minimum number of items that md-auto-shrink
75 * will shrink to (default: 0).
77 function VirtualRepeatContainerDirective() {
79 controller: VirtualRepeatContainerController,
80 template: virtualRepeatContainerTemplate,
81 compile: function virtualRepeatContainerCompile($element, $attrs) {
83 .addClass('md-virtual-repeat-container')
84 .addClass($attrs.hasOwnProperty('mdOrientHorizontal')
85 ? 'md-orient-horizontal'
86 : 'md-orient-vertical');
92 function virtualRepeatContainerTemplate($element) {
93 return '<div class="md-virtual-repeat-scroller">' +
94 '<div class="md-virtual-repeat-sizer"></div>' +
95 '<div class="md-virtual-repeat-offsetter">' +
96 $element[0].innerHTML +
101 * Number of additional elements to render above and below the visible area inside
102 * of the virtual repeat container. A higher number results in less flicker when scrolling
103 * very quickly in Safari, but comes with a higher rendering and dirty-checking cost.
109 function VirtualRepeatContainerController($$rAF, $mdUtil, $mdConstant, $parse, $rootScope, $window, $scope,
111 this.$rootScope = $rootScope;
112 this.$scope = $scope;
113 this.$element = $element;
114 this.$attrs = $attrs;
116 /** @type {number} The width or height of the container */
118 /** @type {number} The scroll width or height of the scroller */
120 /** @type {number} The scrollLeft or scrollTop of the scroller */
121 this.scrollOffset = 0;
122 /** @type {boolean} Whether the scroller is oriented horizontally */
123 this.horizontal = this.$attrs.hasOwnProperty('mdOrientHorizontal');
124 /** @type {!VirtualRepeatController} The repeater inside of this container */
125 this.repeater = null;
126 /** @type {boolean} Whether auto-shrink is enabled */
127 this.autoShrink = this.$attrs.hasOwnProperty('mdAutoShrink');
128 /** @type {number} Minimum number of items to auto-shrink to */
129 this.autoShrinkMin = parseInt(this.$attrs.mdAutoShrinkMin, 10) || 0;
130 /** @type {?number} Original container size when shrank */
131 this.originalSize = null;
132 /** @type {number} Amount to offset the total scroll size by. */
133 this.offsetSize = parseInt(this.$attrs.mdOffsetSize, 10) || 0;
134 /** @type {?string} height or width element style on the container prior to auto-shrinking. */
135 this.oldElementSize = null;
136 /** @type {!number} Maximum amount of pixels allowed for a single DOM element */
137 this.maxElementPixels = $mdConstant.ELEMENT_MAX_PIXELS;
139 if (this.$attrs.mdTopIndex) {
140 /** @type {function(angular.Scope): number} Binds to topIndex on Angular scope */
141 this.bindTopIndex = $parse(this.$attrs.mdTopIndex);
142 /** @type {number} The index of the item that is at the top of the scroll container */
143 this.topIndex = this.bindTopIndex(this.$scope);
145 if (!angular.isDefined(this.topIndex)) {
147 this.bindTopIndex.assign(this.$scope, 0);
150 this.$scope.$watch(this.bindTopIndex, angular.bind(this, function(newIndex) {
151 if (newIndex !== this.topIndex) {
152 this.scrollToIndex(newIndex);
159 this.scroller = $element[0].querySelector('.md-virtual-repeat-scroller');
160 this.sizer = this.scroller.querySelector('.md-virtual-repeat-sizer');
161 this.offsetter = this.scroller.querySelector('.md-virtual-repeat-offsetter');
163 // After the dom stablizes, measure the initial size of the container and
164 // make a best effort at re-measuring as it changes.
165 var boundUpdateSize = angular.bind(this, this.updateSize);
167 $$rAF(angular.bind(this, function() {
170 var debouncedUpdateSize = $mdUtil.debounce(boundUpdateSize, 10, null, false);
171 var jWindow = angular.element($window);
173 // Make one more attempt to get the size if it is 0.
174 // This is not by any means a perfect approach, but there's really no
175 // silver bullet here.
177 debouncedUpdateSize();
180 jWindow.on('resize', debouncedUpdateSize);
181 $scope.$on('$destroy', function() {
182 jWindow.off('resize', debouncedUpdateSize);
185 $scope.$emit('$md-resize-enable');
186 $scope.$on('$md-resize', boundUpdateSize);
191 /** Called by the md-virtual-repeat inside of the container at startup. */
192 VirtualRepeatContainerController.prototype.register = function(repeaterCtrl) {
193 this.repeater = repeaterCtrl;
195 angular.element(this.scroller)
196 .on('scroll wheel touchmove touchend', angular.bind(this, this.handleScroll_));
200 /** @return {boolean} Whether the container is configured for horizontal scrolling. */
201 VirtualRepeatContainerController.prototype.isHorizontal = function() {
202 return this.horizontal;
206 /** @return {number} The size (width or height) of the container. */
207 VirtualRepeatContainerController.prototype.getSize = function() {
213 * Resizes the container.
215 * @param {number} size The new size to set.
217 VirtualRepeatContainerController.prototype.setSize_ = function(size) {
218 var dimension = this.getDimensionName_();
221 this.$element[0].style[dimension] = size + 'px';
225 VirtualRepeatContainerController.prototype.unsetSize_ = function() {
226 this.$element[0].style[this.getDimensionName_()] = this.oldElementSize;
227 this.oldElementSize = null;
231 /** Instructs the container to re-measure its size. */
232 VirtualRepeatContainerController.prototype.updateSize = function() {
233 // If the original size is already determined, we can skip the update.
234 if (this.originalSize) return;
236 this.size = this.isHorizontal()
237 ? this.$element[0].clientWidth
238 : this.$element[0].clientHeight;
240 // Recheck the scroll position after updating the size. This resolves
241 // problems that can result if the scroll position was measured while the
242 // element was display: none or detached from the document.
243 this.handleScroll_();
245 this.repeater && this.repeater.containerUpdated();
249 /** @return {number} The container's scrollHeight or scrollWidth. */
250 VirtualRepeatContainerController.prototype.getScrollSize = function() {
251 return this.scrollSize;
255 VirtualRepeatContainerController.prototype.getDimensionName_ = function() {
256 return this.isHorizontal() ? 'width' : 'height';
261 * Sets the scroller element to the specified size.
263 * @param {number} size The new size.
265 VirtualRepeatContainerController.prototype.sizeScroller_ = function(size) {
266 var dimension = this.getDimensionName_();
267 var crossDimension = this.isHorizontal() ? 'height' : 'width';
269 // Clear any existing dimensions.
270 this.sizer.innerHTML = '';
272 // If the size falls within the browser's maximum explicit size for a single element, we can
273 // set the size and be done. Otherwise, we have to create children that add up the the desired
275 if (size < this.maxElementPixels) {
276 this.sizer.style[dimension] = size + 'px';
278 this.sizer.style[dimension] = 'auto';
279 this.sizer.style[crossDimension] = 'auto';
281 // Divide the total size we have to render into N max-size pieces.
282 var numChildren = Math.floor(size / this.maxElementPixels);
284 // Element template to clone for each max-size piece.
285 var sizerChild = document.createElement('div');
286 sizerChild.style[dimension] = this.maxElementPixels + 'px';
287 sizerChild.style[crossDimension] = '1px';
289 for (var i = 0; i < numChildren; i++) {
290 this.sizer.appendChild(sizerChild.cloneNode(false));
293 // Re-use the element template for the remainder.
294 sizerChild.style[dimension] = (size - (numChildren * this.maxElementPixels)) + 'px';
295 this.sizer.appendChild(sizerChild);
301 * If auto-shrinking is enabled, shrinks or unshrinks as appropriate.
303 * @param {number} size The new size.
305 VirtualRepeatContainerController.prototype.autoShrink_ = function(size) {
306 var shrinkSize = Math.max(size, this.autoShrinkMin * this.repeater.getItemSize());
308 if (this.autoShrink && shrinkSize !== this.size) {
309 if (this.oldElementSize === null) {
310 this.oldElementSize = this.$element[0].style[this.getDimensionName_()];
313 var currentSize = this.originalSize || this.size;
315 if (!currentSize || shrinkSize < currentSize) {
316 if (!this.originalSize) {
317 this.originalSize = this.size;
320 // Now we update the containers size, because shrinking is enabled.
321 this.setSize_(shrinkSize);
322 } else if (this.originalSize !== null) {
323 // Set the size back to our initial size.
326 var _originalSize = this.originalSize;
327 this.originalSize = null;
329 // We determine the repeaters size again, if the original size was zero.
330 // The originalSize needs to be null, to be able to determine the size.
331 if (!_originalSize) this.updateSize();
333 // Apply the original size or the determined size back to the container, because
334 // it has been overwritten before, in the shrink block.
335 this.setSize_(_originalSize || this.size);
338 this.repeater.containerUpdated();
344 * Sets the scrollHeight or scrollWidth. Called by the repeater based on
345 * its item count and item size.
346 * @param {number} itemsSize The total size of the items.
348 VirtualRepeatContainerController.prototype.setScrollSize = function(itemsSize) {
349 var size = itemsSize + this.offsetSize;
350 if (this.scrollSize === size) return;
352 this.sizeScroller_(size);
353 this.autoShrink_(size);
354 this.scrollSize = size;
358 /** @return {number} The container's current scroll offset. */
359 VirtualRepeatContainerController.prototype.getScrollOffset = function() {
360 return this.scrollOffset;
364 * Scrolls to a given scrollTop position.
365 * @param {number} position
367 VirtualRepeatContainerController.prototype.scrollTo = function(position) {
368 this.scroller[this.isHorizontal() ? 'scrollLeft' : 'scrollTop'] = position;
369 this.handleScroll_();
373 * Scrolls the item with the given index to the top of the scroll container.
374 * @param {number} index
376 VirtualRepeatContainerController.prototype.scrollToIndex = function(index) {
377 var itemSize = this.repeater.getItemSize();
378 var itemsLength = this.repeater.itemsLength;
379 if(index > itemsLength) {
380 index = itemsLength - 1;
382 this.scrollTo(itemSize * index);
385 VirtualRepeatContainerController.prototype.resetScroll = function() {
390 VirtualRepeatContainerController.prototype.handleScroll_ = function() {
391 var ltr = document.dir != 'rtl' && document.body.dir != 'rtl';
392 if(!ltr && !this.maxSize) {
393 this.scroller.scrollLeft = this.scrollSize;
394 this.maxSize = this.scroller.scrollLeft;
396 var offset = this.isHorizontal() ?
397 (ltr?this.scroller.scrollLeft : this.maxSize - this.scroller.scrollLeft)
398 : this.scroller.scrollTop;
399 if (offset === this.scrollOffset || offset > this.scrollSize - this.size) return;
401 var itemSize = this.repeater.getItemSize();
402 if (!itemSize) return;
404 var numItems = Math.max(0, Math.floor(offset / itemSize) - NUM_EXTRA);
406 var transform = (this.isHorizontal() ? 'translateX(' : 'translateY(') +
407 (!this.isHorizontal() || ltr ? (numItems * itemSize) : - (numItems * itemSize)) + 'px)';
409 this.scrollOffset = offset;
410 this.offsetter.style.webkitTransform = transform;
411 this.offsetter.style.transform = transform;
413 if (this.bindTopIndex) {
414 var topIndex = Math.floor(offset / itemSize);
415 if (topIndex !== this.topIndex && topIndex < this.repeater.getItemCount()) {
416 this.topIndex = topIndex;
417 this.bindTopIndex.assign(this.$scope, topIndex);
418 if (!this.$rootScope.$$phase) this.$scope.$digest();
422 this.repeater.containerUpdated();
428 * @name mdVirtualRepeat
429 * @module material.components.virtualRepeat
433 * `md-virtual-repeat` specifies an element to repeat using virtual scrolling.
435 * Virtual repeat is a limited substitute for ng-repeat that renders only
436 * enough DOM nodes to fill the container and recycling them as the user scrolls.
438 * Arrays, but not objects are supported for iteration.
439 * Track by, as alias, and (key, value) syntax are not supported.
441 * ### On-Demand Async Item Loading
443 * When using the `md-on-demand` attribute and loading some asynchronous data, the `getItemAtIndex` function will
444 * mostly return nothing.
447 * DynamicItems.prototype.getItemAtIndex = function(index) {
448 * if (this.pages[index]) {
449 * return this.pages[index];
451 * // This is an asynchronous action and does not return any value.
452 * this.loadPage(index);
457 * This means that the VirtualRepeat will not have any value for the given index.<br/>
458 * After the data loading completed, the user expects the VirtualRepeat to recognize the change.
460 * To make sure that the VirtualRepeat properly detects any change, you need to run the operation
464 * DynamicItems.prototype.loadPage = function(index) {
467 * // Trigger a new digest by using $timeout
468 * $timeout(function() {
469 * self.pages[index] = Data;
474 * > <b>Note:</b> Please also review the
475 * <a ng-href="api/directive/mdVirtualRepeatContainer">VirtualRepeatContainer</a> documentation
476 * for more information.
480 * <md-virtual-repeat-container>
481 * <div md-virtual-repeat="i in items">Hello {{i}}!</div>
482 * </md-virtual-repeat-container>
484 * <md-virtual-repeat-container md-orient-horizontal>
485 * <div md-virtual-repeat="i in items" md-item-size="20">Hello {{i}}!</div>
486 * </md-virtual-repeat-container>
489 * @param {number=} md-item-size The height or width of the repeated elements (which must be
490 * identical for each element). Optional. Will attempt to read the size from the dom if missing,
491 * but still assumes that all repeated nodes have same height or width.
492 * @param {string=} md-extra-name Evaluates to an additional name to which the current iterated item
493 * can be assigned on the repeated scope (needed for use in `md-autocomplete`).
494 * @param {boolean=} md-on-demand When present, treats the md-virtual-repeat argument as an object
495 * that can fetch rows rather than an array.
497 * **NOTE:** This object must implement the following interface with two (2) methods:
499 * - `getItemAtIndex: function(index) [object]` The item at that index or null if it is not yet
500 * loaded (it should start downloading the item in that case).
501 * - `getLength: function() [number]` The data length to which the repeater container
502 * should be sized. Ideally, when the count is known, this method should return it.
503 * Otherwise, return a higher number than the currently loaded items to produce an
504 * infinite-scroll behavior.
506 function VirtualRepeatDirective($parse) {
508 controller: VirtualRepeatController,
510 require: ['mdVirtualRepeat', '^^mdVirtualRepeatContainer'],
513 transclude: 'element',
514 compile: function VirtualRepeatCompile($element, $attrs) {
515 var expression = $attrs.mdVirtualRepeat;
516 var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)\s*$/);
517 var repeatName = match[1];
518 var repeatListExpression = $parse(match[2]);
519 var extraName = $attrs.mdExtraName && $parse($attrs.mdExtraName);
521 return function VirtualRepeatLink($scope, $element, $attrs, ctrl, $transclude) {
522 ctrl[0].link_(ctrl[1], $transclude, repeatName, repeatListExpression, extraName);
530 function VirtualRepeatController($scope, $element, $attrs, $browser, $document, $rootScope,
532 this.$scope = $scope;
533 this.$element = $element;
534 this.$attrs = $attrs;
535 this.$browser = $browser;
536 this.$document = $document;
537 this.$rootScope = $rootScope;
540 /** @type {boolean} Whether we are in on-demand mode. */
541 this.onDemand = $mdUtil.parseAttributeBoolean($attrs.mdOnDemand);
542 /** @type {!Function} Backup reference to $browser.$$checkUrlChange */
543 this.browserCheckUrlChange = $browser.$$checkUrlChange;
544 /** @type {number} Most recent starting repeat index (based on scroll offset) */
545 this.newStartIndex = 0;
546 /** @type {number} Most recent ending repeat index (based on scroll offset) */
547 this.newEndIndex = 0;
548 /** @type {number} Most recent end visible index (based on scroll offset) */
549 this.newVisibleEnd = 0;
550 /** @type {number} Previous starting repeat index (based on scroll offset) */
552 /** @type {number} Previous ending repeat index (based on scroll offset) */
554 // TODO: measure width/height of first element from dom if not provided.
556 /** @type {?number} Height/width of repeated elements. */
557 this.itemSize = $scope.$eval($attrs.mdItemSize) || null;
559 /** @type {boolean} Whether this is the first time that items are rendered. */
560 this.isFirstRender = true;
563 * @private {boolean} Whether the items in the list are already being updated. Used to prevent
564 * nested calls to virtualRepeatUpdate_.
566 this.isVirtualRepeatUpdating_ = false;
568 /** @type {number} Most recently seen length of items. */
569 this.itemsLength = 0;
572 * @type {!Function} Unwatch callback for item size (when md-items-size is
573 * not specified), or angular.noop otherwise.
575 this.unwatchItemSize_ = angular.noop;
578 * Presently rendered blocks by repeat index.
579 * @type {Object<number, !VirtualRepeatController.Block}
582 /** @type {Array<!VirtualRepeatController.Block>} A pool of presently unused blocks. */
583 this.pooledBlocks = [];
585 $scope.$on('$destroy', angular.bind(this, this.cleanupBlocks_));
590 * An object representing a repeated item.
591 * @typedef {{element: !jqLite, new: boolean, scope: !angular.Scope}}
593 VirtualRepeatController.Block;
597 * Called at startup by the md-virtual-repeat postLink function.
598 * @param {!VirtualRepeatContainerController} container The container's controller.
599 * @param {!Function} transclude The repeated element's bound transclude function.
600 * @param {string} repeatName The left hand side of the repeat expression, indicating
601 * the name for each item in the array.
602 * @param {!Function} repeatListExpression A compiled expression based on the right hand side
603 * of the repeat expression. Points to the array to repeat over.
604 * @param {string|undefined} extraName The optional extra repeatName.
606 VirtualRepeatController.prototype.link_ =
607 function(container, transclude, repeatName, repeatListExpression, extraName) {
608 this.container = container;
609 this.transclude = transclude;
610 this.repeatName = repeatName;
611 this.rawRepeatListExpression = repeatListExpression;
612 this.extraName = extraName;
615 this.repeatListExpression = angular.bind(this, this.repeatListExpression_);
617 this.container.register(this);
621 /** @private Cleans up unused blocks. */
622 VirtualRepeatController.prototype.cleanupBlocks_ = function() {
623 angular.forEach(this.pooledBlocks, function cleanupBlock(block) {
624 block.element.remove();
629 /** @private Attempts to set itemSize by measuring a repeated element in the dom */
630 VirtualRepeatController.prototype.readItemSize_ = function() {
632 // itemSize was successfully read in a different asynchronous call.
636 this.items = this.repeatListExpression(this.$scope);
637 this.parentNode = this.$element[0].parentNode;
638 var block = this.getBlock_(0);
639 if (!block.element[0].parentNode) {
640 this.parentNode.appendChild(block.element[0]);
643 this.itemSize = block.element[0][
644 this.container.isHorizontal() ? 'offsetWidth' : 'offsetHeight'] || null;
646 this.blocks[0] = block;
650 this.containerUpdated();
656 * Returns the user-specified repeat list, transforming it into an array-like
657 * object in the case of infinite scroll/dynamic load mode.
658 * @param {!angular.Scope} The scope.
659 * @return {!Array|!Object} An array or array-like object for iteration.
661 VirtualRepeatController.prototype.repeatListExpression_ = function(scope) {
662 var repeatList = this.rawRepeatListExpression(scope);
664 if (this.onDemand && repeatList) {
665 var virtualList = new VirtualRepeatModelArrayLike(repeatList);
666 virtualList.$$includeIndexes(this.newStartIndex, this.newVisibleEnd);
675 * Called by the container. Informs us that the containers scroll or size has
678 VirtualRepeatController.prototype.containerUpdated = function() {
679 // If itemSize is unknown, attempt to measure it.
680 if (!this.itemSize) {
681 // Make sure to clean up watchers if we can (see #8178)
682 if(this.unwatchItemSize_ && this.unwatchItemSize_ !== angular.noop){
683 this.unwatchItemSize_();
685 this.unwatchItemSize_ = this.$scope.$watchCollection(
686 this.repeatListExpression,
687 angular.bind(this, function(items) {
688 if (items && items.length) {
689 this.readItemSize_();
692 if (!this.$rootScope.$$phase) this.$scope.$digest();
695 } else if (!this.sized) {
696 this.items = this.repeatListExpression(this.$scope);
700 this.unwatchItemSize_();
702 this.$scope.$watchCollection(this.repeatListExpression,
703 angular.bind(this, function(items, oldItems) {
704 if (!this.isVirtualRepeatUpdating_) {
705 this.virtualRepeatUpdate_(items, oldItems);
710 this.updateIndexes_();
712 if (this.newStartIndex !== this.startIndex ||
713 this.newEndIndex !== this.endIndex ||
714 this.container.getScrollOffset() > this.container.getScrollSize()) {
715 if (this.items instanceof VirtualRepeatModelArrayLike) {
716 this.items.$$includeIndexes(this.newStartIndex, this.newEndIndex);
718 this.virtualRepeatUpdate_(this.items, this.items);
724 * Called by the container. Returns the size of a single repeated item.
725 * @return {?number} Size of a repeated item.
727 VirtualRepeatController.prototype.getItemSize = function() {
728 return this.itemSize;
733 * Called by the container. Returns the size of a single repeated item.
734 * @return {?number} Size of a repeated item.
736 VirtualRepeatController.prototype.getItemCount = function() {
737 return this.itemsLength;
742 * Updates the order and visible offset of repeated blocks in response to scrolling
746 VirtualRepeatController.prototype.virtualRepeatUpdate_ = function(items, oldItems) {
747 this.isVirtualRepeatUpdating_ = true;
749 var itemsLength = items && items.length || 0;
750 var lengthChanged = false;
752 // If the number of items shrank, keep the scroll position.
753 if (this.items && itemsLength < this.items.length && this.container.getScrollOffset() !== 0) {
755 var previousScrollOffset = this.container.getScrollOffset();
756 this.container.resetScroll();
757 this.container.scrollTo(previousScrollOffset);
760 if (itemsLength !== this.itemsLength) {
761 lengthChanged = true;
762 this.itemsLength = itemsLength;
766 if (items !== oldItems || lengthChanged) {
767 this.updateIndexes_();
770 this.parentNode = this.$element[0].parentNode;
773 this.container.setScrollSize(itemsLength * this.itemSize);
776 if (this.isFirstRender) {
777 this.isFirstRender = false;
778 var startIndex = this.$attrs.mdStartIndex ?
779 this.$scope.$eval(this.$attrs.mdStartIndex) :
780 this.container.topIndex;
781 this.container.scrollToIndex(startIndex);
784 // Detach and pool any blocks that are no longer in the viewport.
785 Object.keys(this.blocks).forEach(function(blockIndex) {
786 var index = parseInt(blockIndex, 10);
787 if (index < this.newStartIndex || index >= this.newEndIndex) {
788 this.poolBlock_(index);
792 // Add needed blocks.
793 // For performance reasons, temporarily block browser url checks as we digest
794 // the restored block scopes ($$checkUrlChange reads window.location to
795 // check for changes and trigger route change, etc, which we don't need when
796 // trying to scroll at 60fps).
797 this.$browser.$$checkUrlChange = angular.noop;
803 // Collect blocks at the top.
804 for (i = this.newStartIndex; i < this.newEndIndex && this.blocks[i] == null; i++) {
805 block = this.getBlock_(i);
806 this.updateBlock_(block, i);
807 newStartBlocks.push(block);
810 // Update blocks that are already rendered.
811 for (; this.blocks[i] != null; i++) {
812 this.updateBlock_(this.blocks[i], i);
814 var maxIndex = i - 1;
816 // Collect blocks at the end.
817 for (; i < this.newEndIndex; i++) {
818 block = this.getBlock_(i);
819 this.updateBlock_(block, i);
820 newEndBlocks.push(block);
823 // Attach collected blocks to the document.
824 if (newStartBlocks.length) {
825 this.parentNode.insertBefore(
826 this.domFragmentFromBlocks_(newStartBlocks),
827 this.$element[0].nextSibling);
829 if (newEndBlocks.length) {
830 this.parentNode.insertBefore(
831 this.domFragmentFromBlocks_(newEndBlocks),
832 this.blocks[maxIndex] && this.blocks[maxIndex].element[0].nextSibling);
835 // Restore $$checkUrlChange.
836 this.$browser.$$checkUrlChange = this.browserCheckUrlChange;
838 this.startIndex = this.newStartIndex;
839 this.endIndex = this.newEndIndex;
841 this.isVirtualRepeatUpdating_ = false;
846 * @param {number} index Where the block is to be in the repeated list.
847 * @return {!VirtualRepeatController.Block} A new or pooled block to place at the specified index.
850 VirtualRepeatController.prototype.getBlock_ = function(index) {
851 if (this.pooledBlocks.length) {
852 return this.pooledBlocks.pop();
856 this.transclude(angular.bind(this, function(clone, scope) {
863 this.updateScope_(scope, index);
864 this.parentNode.appendChild(clone[0]);
872 * Updates and if not in a digest cycle, digests the specified block's scope to the data
873 * at the specified index.
874 * @param {!VirtualRepeatController.Block} block The block whose scope should be updated.
875 * @param {number} index The index to set.
878 VirtualRepeatController.prototype.updateBlock_ = function(block, index) {
879 this.blocks[index] = block;
882 (block.scope.$index === index && block.scope[this.repeatName] === this.items[index])) {
887 // Update and digest the block's scope.
888 this.updateScope_(block.scope, index);
890 // Perform digest before reattaching the block.
891 // Any resulting synchronous dom mutations should be much faster as a result.
892 // This might break some directives, but I'm going to try it for now.
893 if (!this.$rootScope.$$phase) {
894 block.scope.$digest();
900 * Updates scope to the data at the specified index.
901 * @param {!angular.Scope} scope The scope which should be updated.
902 * @param {number} index The index to set.
905 VirtualRepeatController.prototype.updateScope_ = function(scope, index) {
906 scope.$index = index;
907 scope[this.repeatName] = this.items && this.items[index];
908 if (this.extraName) scope[this.extraName(this.$scope)] = this.items[index];
913 * Pools the block at the specified index (Pulls its element out of the dom and stores it).
914 * @param {number} index The index at which the block to pool is stored.
917 VirtualRepeatController.prototype.poolBlock_ = function(index) {
918 this.pooledBlocks.push(this.blocks[index]);
919 this.parentNode.removeChild(this.blocks[index].element[0]);
920 delete this.blocks[index];
925 * Produces a dom fragment containing the elements from the list of blocks.
926 * @param {!Array<!VirtualRepeatController.Block>} blocks The blocks whose elements
927 * should be added to the document fragment.
928 * @return {DocumentFragment}
931 VirtualRepeatController.prototype.domFragmentFromBlocks_ = function(blocks) {
932 var fragment = this.$document[0].createDocumentFragment();
933 blocks.forEach(function(block) {
934 fragment.appendChild(block.element[0]);
941 * Updates start and end indexes based on length of repeated items and container size.
944 VirtualRepeatController.prototype.updateIndexes_ = function() {
945 var itemsLength = this.items ? this.items.length : 0;
946 var containerLength = Math.ceil(this.container.getSize() / this.itemSize);
948 this.newStartIndex = Math.max(0, Math.min(
949 itemsLength - containerLength,
950 Math.floor(this.container.getScrollOffset() / this.itemSize)));
951 this.newVisibleEnd = this.newStartIndex + containerLength + NUM_EXTRA;
952 this.newEndIndex = Math.min(itemsLength, this.newVisibleEnd);
953 this.newStartIndex = Math.max(0, this.newStartIndex - NUM_EXTRA);
957 * This VirtualRepeatModelArrayLike class enforces the interface requirements
958 * for infinite scrolling within a mdVirtualRepeatContainer. An object with this
959 * interface must implement the following interface with two (2) methods:
961 * getItemAtIndex: function(index) -> item at that index or null if it is not yet
962 * loaded (It should start downloading the item in that case).
964 * getLength: function() -> number The data legnth to which the repeater container
965 * should be sized. Ideally, when the count is known, this method should return it.
966 * Otherwise, return a higher number than the currently loaded items to produce an
967 * infinite-scroll behavior.
971 * <md-virtual-repeat-container md-orient-horizontal>
972 * <div md-virtual-repeat="i in items" md-on-demand>
975 * </md-virtual-repeat-container>
979 function VirtualRepeatModelArrayLike(model) {
980 if (!angular.isFunction(model.getItemAtIndex) ||
981 !angular.isFunction(model.getLength)) {
982 throw Error('When md-on-demand is enabled, the Object passed to md-virtual-repeat must implement ' +
983 'functions getItemAtIndex() and getLength() ');
990 VirtualRepeatModelArrayLike.prototype.$$includeIndexes = function(start, end) {
991 for (var i = start; i < end; i++) {
992 if (!this.hasOwnProperty(i)) {
993 this[i] = this.model.getItemAtIndex(i);
996 this.length = this.model.getLength();
999 ngmaterial.components.virtualRepeat = angular.module("material.components.virtualRepeat");