_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q19900
removeTab
train
function removeTab (tabData) { if (destroyed) return; var selectedIndex = ctrl.selectedIndex, tab = ctrl.tabs.splice(tabData.getIndex(), 1)[ 0 ]; refreshIndex(); // when removing a tab, if the selected index did not change, we have to manually trigger the // tab select/deselect events if (ctrl.selectedIndex === selectedIndex) { tab.scope.deselect(); ctrl.tabs[ ctrl.selectedIndex ] && ctrl.tabs[ ctrl.selectedIndex ].scope.select(); } $mdUtil.nextTick(function () { updatePagination(); ctrl.offsetLeft = fixOffset(ctrl.offsetLeft); }); }
javascript
{ "resource": "" }
q19901
insertTab
train
function insertTab (tabData, index) { var hasLoaded = loaded; var proto = { getIndex: function () { return ctrl.tabs.indexOf(tab); }, isActive: function () { return this.getIndex() === ctrl.selectedIndex; }, isLeft: function () { return this.getIndex() < ctrl.selectedIndex; }, isRight: function () { return this.getIndex() > ctrl.selectedIndex; }, shouldRender: function () { return !ctrl.noDisconnect || this.isActive(); }, hasFocus: function () { return ctrl.styleTabItemFocus && ctrl.hasFocus && this.getIndex() === ctrl.focusIndex; }, id: $mdUtil.nextUid(), hasContent: !!(tabData.template && tabData.template.trim()) }; var tab = angular.extend(proto, tabData); if (angular.isDefined(index)) { ctrl.tabs.splice(index, 0, tab); } else { ctrl.tabs.push(tab); } processQueue(); updateHasContent(); $mdUtil.nextTick(function () { updatePagination(); setAriaControls(tab); // if autoselect is enabled, select the newly added tab if (hasLoaded && ctrl.autoselect) { $mdUtil.nextTick(function () { $mdUtil.nextTick(function () { select(ctrl.tabs.indexOf(tab)); }); }); } }); return tab; }
javascript
{ "resource": "" }
q19902
getElements
train
function getElements () { var elements = {}; var node = $element[0]; // gather tab bar elements elements.wrapper = node.querySelector('md-tabs-wrapper'); elements.canvas = elements.wrapper.querySelector('md-tabs-canvas'); elements.paging = elements.canvas.querySelector('md-pagination-wrapper'); elements.inkBar = elements.paging.querySelector('md-ink-bar'); elements.nextButton = node.querySelector('md-next-button'); elements.prevButton = node.querySelector('md-prev-button'); elements.contents = node.querySelectorAll('md-tabs-content-wrapper > md-tab-content'); elements.tabs = elements.paging.querySelectorAll('md-tab-item'); elements.dummies = elements.canvas.querySelectorAll('md-dummy-tab'); return elements; }
javascript
{ "resource": "" }
q19903
canPageForward
train
function canPageForward () { var elements = getElements(); var lastTab = elements.tabs[ elements.tabs.length - 1 ]; if (isRtl()) { return ctrl.offsetLeft < elements.paging.offsetWidth - elements.canvas.offsetWidth; } return lastTab && lastTab.offsetLeft + lastTab.offsetWidth > elements.canvas.clientWidth + ctrl.offsetLeft; }
javascript
{ "resource": "" }
q19904
getFocusedTabId
train
function getFocusedTabId() { var focusedTab = ctrl.tabs[ctrl.focusIndex]; if (!focusedTab || !focusedTab.id) { return null; } return 'tab-item-' + focusedTab.id; }
javascript
{ "resource": "" }
q19905
shouldPaginate
train
function shouldPaginate () { var shouldPaginate; if (ctrl.noPagination || !loaded) return false; var canvasWidth = $element.prop('clientWidth'); angular.forEach(getElements().tabs, function (tab) { canvasWidth -= tab.offsetWidth; }); shouldPaginate = canvasWidth < 0; // Work around width calculation issues on IE11 when pagination is enabled. // Don't do this on other browsers because it breaks scroll to new tab animation. if ($mdUtil.msie) { if (shouldPaginate) { getElements().paging.style.width = '999999px'; } else { getElements().paging.style.width = undefined; } } return shouldPaginate; }
javascript
{ "resource": "" }
q19906
getNearestSafeIndex
train
function getNearestSafeIndex (newIndex) { if (newIndex === -1) return -1; var maxOffset = Math.max(ctrl.tabs.length - newIndex, newIndex), i, tab; for (i = 0; i <= maxOffset; i++) { tab = ctrl.tabs[ newIndex + i ]; if (tab && (tab.scope.disabled !== true)) return tab.getIndex(); tab = ctrl.tabs[ newIndex - i ]; if (tab && (tab.scope.disabled !== true)) return tab.getIndex(); } return newIndex; }
javascript
{ "resource": "" }
q19907
updateTabOrder
train
function updateTabOrder () { var selectedItem = ctrl.tabs[ ctrl.selectedIndex ], focusItem = ctrl.tabs[ ctrl.focusIndex ]; ctrl.tabs = ctrl.tabs.sort(function (a, b) { return a.index - b.index; }); ctrl.selectedIndex = ctrl.tabs.indexOf(selectedItem); ctrl.focusIndex = ctrl.tabs.indexOf(focusItem); }
javascript
{ "resource": "" }
q19908
incrementIndex
train
function incrementIndex (inc, focus) { var newIndex, key = focus ? 'focusIndex' : 'selectedIndex', index = ctrl[ key ]; for (newIndex = index + inc; ctrl.tabs[ newIndex ] && ctrl.tabs[ newIndex ].scope.disabled; newIndex += inc) { /* do nothing */ } newIndex = (index + inc + ctrl.tabs.length) % ctrl.tabs.length; if (ctrl.tabs[ newIndex ]) { ctrl[ key ] = newIndex; } }
javascript
{ "resource": "" }
q19909
redirectFocus
train
function redirectFocus () { ctrl.styleTabItemFocus = ($mdInteraction.getLastInteractionType() === 'keyboard'); var tabToFocus = getElements().tabs[ctrl.focusIndex]; if (tabToFocus) { tabToFocus.focus(); } }
javascript
{ "resource": "" }
q19910
updateHasContent
train
function updateHasContent () { var hasContent = false; var i; for (i = 0; i < ctrl.tabs.length; i++) { if (ctrl.tabs[i].hasContent) { hasContent = true; break; } } ctrl.hasContent = hasContent; }
javascript
{ "resource": "" }
q19911
refreshIndex
train
function refreshIndex () { ctrl.selectedIndex = getNearestSafeIndex(ctrl.selectedIndex); ctrl.focusIndex = getNearestSafeIndex(ctrl.focusIndex); }
javascript
{ "resource": "" }
q19912
updateHeightFromContent
train
function updateHeightFromContent () { if (!ctrl.dynamicHeight) return $element.css('height', ''); if (!ctrl.tabs.length) return queue.push(updateHeightFromContent); var elements = getElements(); var tabContent = elements.contents[ ctrl.selectedIndex ], contentHeight = tabContent ? tabContent.offsetHeight : 0, tabsHeight = elements.wrapper.offsetHeight, newHeight = contentHeight + tabsHeight, currentHeight = $element.prop('clientHeight'); if (currentHeight === newHeight) return; // Adjusts calculations for when the buttons are bottom-aligned since this relies on absolute // positioning. This should probably be cleaned up if a cleaner solution is possible. if ($element.attr('md-align-tabs') === 'bottom') { currentHeight -= tabsHeight; newHeight -= tabsHeight; // Need to include bottom border in these calculations if ($element.attr('md-border-bottom') !== undefined) { ++currentHeight; } } // Lock during animation so the user can't change tabs locked = true; var fromHeight = { height: currentHeight + 'px' }, toHeight = { height: newHeight + 'px' }; // Set the height to the current, specific pixel height to fix a bug on iOS where the height // first animates to 0, then back to the proper height causing a visual glitch $element.css(fromHeight); // Animate the height from the old to the new $animateCss($element, { from: fromHeight, to: toHeight, easing: 'cubic-bezier(0.35, 0, 0.25, 1)', duration: 0.5 }).start().done(function () { // Then (to fix the same iOS issue as above), disable transitions and remove the specific // pixel height so the height can size with browser width/content changes, etc. $element.css({ transition: 'none', height: '' }); // In the next tick, re-allow transitions (if we do it all at once, $element.css is "smart" // enough to batch it for us instead of doing it immediately, which undoes the original // transition: none) $mdUtil.nextTick(function() { $element.css('transition', ''); }); // And unlock so tab changes can occur locked = false; }); }
javascript
{ "resource": "" }
q19913
updateInkBarStyles
train
function updateInkBarStyles (previousTotalWidth, previousWidthOfTabItems) { if (ctrl.noInkBar) { return; } var elements = getElements(); if (!elements.tabs[ ctrl.selectedIndex ]) { angular.element(elements.inkBar).css({ left: 'auto', right: 'auto' }); return; } if (!ctrl.tabs.length) { queue.push(ctrl.updateInkBarStyles); return; } // If the element is not visible, we will not be able to calculate sizes until it becomes // visible. We should treat that as a resize event rather than just updating the ink bar. if (!$element.prop('offsetParent')) { handleResizeWhenVisible(); return; } var index = ctrl.selectedIndex, totalWidth = elements.paging.offsetWidth, tab = elements.tabs[ index ], left = tab.offsetLeft, right = totalWidth - left - tab.offsetWidth; if (ctrl.shouldCenterTabs) { // We need to use the same calculate process as in the pagination wrapper, to avoid rounding // deviations. var totalWidthOfTabItems = calcTabsWidth(elements.tabs); if (totalWidth > totalWidthOfTabItems && previousTotalWidth !== totalWidth && previousWidthOfTabItems !== totalWidthOfTabItems) { $timeout(updateInkBarStyles, 0, true, totalWidth, totalWidthOfTabItems); } } updateInkBarClassName(); angular.element(elements.inkBar).css({ left: left + 'px', right: right + 'px' }); }
javascript
{ "resource": "" }
q19914
attachRipple
train
function attachRipple (scope, element) { var elements = getElements(); var options = { colorElement: angular.element(elements.inkBar) }; $mdTabInkRipple.attach(scope, element, options); }
javascript
{ "resource": "" }
q19915
setAriaControls
train
function setAriaControls (tab) { if (tab.hasContent) { var nodes = $element[0].querySelectorAll('[md-tab-id="' + tab.id + '"]'); angular.element(nodes).attr('aria-controls', ctrl.tabContentPrefix + tab.id); } }
javascript
{ "resource": "" }
q19916
copyAttributes
train
function copyAttributes(source, destination, extraAttrs) { var copiedAttrs = $mdUtil.prefixer([ 'ng-if', 'ng-click', 'ng-dblclick', 'aria-label', 'ng-disabled', 'ui-sref', 'href', 'ng-href', 'rel', 'target', 'ng-attr-ui-sref', 'ui-sref-opts', 'download' ]); if (extraAttrs) { copiedAttrs = copiedAttrs.concat($mdUtil.prefixer(extraAttrs)); } angular.forEach(copiedAttrs, function(attr) { if (source.hasAttribute(attr)) { destination.setAttribute(attr, source.getAttribute(attr)); source.removeAttribute(attr); } }); }
javascript
{ "resource": "" }
q19917
InkRippleCtrl
train
function InkRippleCtrl ($scope, $element, rippleOptions, $window, $timeout, $mdUtil, $mdColorUtil) { this.$window = $window; this.$timeout = $timeout; this.$mdUtil = $mdUtil; this.$mdColorUtil = $mdColorUtil; this.$scope = $scope; this.$element = $element; this.options = rippleOptions; this.mousedown = false; this.ripples = []; this.timeout = null; // Stores a reference to the most-recent ripple timeout this.lastRipple = null; $mdUtil.valueOnUse(this, 'container', this.createContainer); this.$element.addClass('md-ink-ripple'); // attach method for unit tests ($element.controller('mdInkRipple') || {}).createRipple = angular.bind(this, this.createRipple); ($element.controller('mdInkRipple') || {}).setColor = angular.bind(this, this.color); this.bindEvents(); }
javascript
{ "resource": "" }
q19918
getElementColor
train
function getElementColor () { var items = self.options && self.options.colorElement ? self.options.colorElement : []; var elem = items.length ? items[ 0 ] : self.$element[ 0 ]; return elem ? self.$window.getComputedStyle(elem).color : 'rgb(0,0,0)'; }
javascript
{ "resource": "" }
q19919
defaultFormatDate
train
function defaultFormatDate(date, timezone) { if (!date) { return ''; } // All of the dates created through ng-material *should* be set to midnight. // If we encounter a date where the localeTime shows at 11pm instead of midnight, // we have run into an issue with DST where we need to increment the hour by one: // var d = new Date(1992, 9, 8, 0, 0, 0); // d.toLocaleString(); // == "10/7/1992, 11:00:00 PM" var localeTime = date.toLocaleTimeString(); var formatDate = date; if (date.getHours() === 0 && (localeTime.indexOf('11:') !== -1 || localeTime.indexOf('23:') !== -1)) { formatDate = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 1, 0, 0); } return $filter('date')(formatDate, 'M/d/yyyy', timezone); }
javascript
{ "resource": "" }
q19920
defaultLongDateFormatter
train
function defaultLongDateFormatter(date) { // Example: 'Thursday June 18 2015' return [ service.days[date.getDay()], service.months[date.getMonth()], service.dates[date.getDate()], date.getFullYear() ].join(' '); }
javascript
{ "resource": "" }
q19921
calendarDirective
train
function calendarDirective() { return { template: '<table aria-hidden="true" class="md-calendar-day-header"><thead></thead></table>' + '<div class="md-calendar-scroll-mask">' + '<md-virtual-repeat-container class="md-calendar-scroll-container" ' + 'md-offset-size="' + (TBODY_SINGLE_ROW_HEIGHT - TBODY_HEIGHT) + '">' + '<table role="grid" tabindex="0" class="md-calendar" aria-readonly="true">' + '<tbody ' + 'md-calendar-month-body ' + 'role="rowgroup" ' + 'md-virtual-repeat="i in monthCtrl.items" ' + 'md-month-offset="$index" ' + 'class="md-calendar-month" ' + 'md-start-index="monthCtrl.getSelectedMonthIndex()" ' + 'md-item-size="' + TBODY_HEIGHT + '">' + // The <tr> ensures that the <tbody> will always have the // proper height, even if it's empty. If it's content is // compiled, the <tr> will be overwritten. '<tr aria-hidden="true" md-force-height="\'' + TBODY_HEIGHT + 'px\'"></tr>' + '</tbody>' + '</table>' + '</md-virtual-repeat-container>' + '</div>', require: ['^^mdCalendar', 'mdCalendarMonth'], controller: CalendarMonthCtrl, controllerAs: 'monthCtrl', bindToController: true, link: function(scope, element, attrs, controllers) { var calendarCtrl = controllers[0]; var monthCtrl = controllers[1]; monthCtrl.initialize(calendarCtrl); } }; }
javascript
{ "resource": "" }
q19922
CalendarMonthCtrl
train
function CalendarMonthCtrl($element, $scope, $animate, $q, $$mdDateUtil, $mdDateLocale) { /** @final {!angular.JQLite} */ this.$element = $element; /** @final {!angular.Scope} */ this.$scope = $scope; /** @final {!angular.$animate} */ this.$animate = $animate; /** @final {!angular.$q} */ this.$q = $q; /** @final */ this.dateUtil = $$mdDateUtil; /** @final */ this.dateLocale = $mdDateLocale; /** @final {HTMLElement} */ this.calendarScroller = $element[0].querySelector('.md-virtual-repeat-scroller'); /** @type {boolean} */ this.isInitialized = false; /** @type {boolean} */ this.isMonthTransitionInProgress = false; var self = this; /** * Handles a click event on a date cell. * Created here so that every cell can use the same function instance. * @this {HTMLTableCellElement} The cell that was clicked. */ this.cellClickHandler = function() { var timestamp = $$mdDateUtil.getTimestampFromNode(this); self.$scope.$apply(function() { self.calendarCtrl.setNgModelValue(timestamp); }); }; /** * Handles click events on the month headers. Switches * the calendar to the year view. * @this {HTMLTableCellElement} The cell that was clicked. */ this.headerClickHandler = function() { self.calendarCtrl.setCurrentView('year', $$mdDateUtil.getTimestampFromNode(this)); }; }
javascript
{ "resource": "" }
q19923
MdNavItemController
train
function MdNavItemController($element) { /** @private @const {!angular.JQLite} */ this._$element = $element; // Data-bound variables /** @const {?Function} */ this.mdNavClick; /** @const {?string} */ this.mdNavHref; /** @const {?string} */ this.mdNavSref; /** @const {?Object} */ this.srefOpts; /** @const {?string} */ this.name; /** @type {string} */ this.navItemAriaLabel; // State variables /** @private {boolean} */ this._selected = false; /** @private {boolean} */ this._focused = false; }
javascript
{ "resource": "" }
q19924
mapExistingElement
train
function mapExistingElement(name) { if (metaElements[name]) { return true; } var element = document.getElementsByName(name)[0]; if (!element) { return false; } metaElements[name] = angular.element(element); return true; }
javascript
{ "resource": "" }
q19925
delayedQuerySearch
train
function delayedQuerySearch(criteria) { if (!pendingSearch || !debounceSearch()) { cancelSearch(); return pendingSearch = $q(function(resolve, reject) { // Simulate async search... (after debouncing) cancelSearch = reject; $timeout(function() { resolve(self.querySearch(criteria)); refreshDebounce(); }, Math.random() * 500, true); }); } return pendingSearch; }
javascript
{ "resource": "" }
q19926
MdContactChips
train
function MdContactChips($mdTheming, $mdUtil) { return { template: function(element, attrs) { return MD_CONTACT_CHIPS_TEMPLATE; }, restrict: 'E', controller: 'MdContactChipsCtrl', controllerAs: '$mdContactChipsCtrl', bindToController: true, compile: compile, scope: { contactQuery: '&mdContacts', placeholder: '@?', secondaryPlaceholder: '@?', contactName: '@mdContactName', contactImage: '@mdContactImage', contactEmail: '@mdContactEmail', contacts: '=ngModel', ngChange: '&?', requireMatch: '=?mdRequireMatch', minLength: '=?mdMinLength', highlightFlags: '@?mdHighlightFlags', chipAppendDelay: '@?mdChipAppendDelay', separatorKeys: '=?mdSeparatorKeys', removedMessage: '@?mdRemovedMessage', inputAriaDescribedBy: '@?inputAriaDescribedby', inputAriaLabelledBy: '@?inputAriaLabelledby', inputAriaLabel: '@?', containerHint: '@?', containerEmptyHint: '@?', deleteHint: '@?' } }; function compile(element, attr) { return function postLink(scope, element, attrs, controllers) { var contactChipsController = controllers; $mdUtil.initOptionalProperties(scope, attr); $mdTheming(element); element.attr('tabindex', '-1'); attrs.$observe('mdChipAppendDelay', function(newValue) { contactChipsController.chipAppendDelay = newValue; }); }; } }
javascript
{ "resource": "" }
q19927
getRepeatMode
train
function getRepeatMode(modeStr) { if (!modeStr) { return REPEAT_VIRTUAL; } modeStr = modeStr.toLowerCase(); return REPEAT_MODES.indexOf(modeStr) > -1 ? modeStr : REPEAT_VIRTUAL; }
javascript
{ "resource": "" }
q19928
train
function (target, key, expectedVal) { var hasValue = false; if (target && target.length) { var computedStyles = $window.getComputedStyle(target[0]); hasValue = angular.isDefined(computedStyles[key]) && (expectedVal ? computedStyles[key] == expectedVal : true); } return hasValue; }
javascript
{ "resource": "" }
q19929
train
function(nodes) { nodes = nodes || []; var results = []; for (var i = 0; i < nodes.length; ++i) { results.push(nodes.item(i)); } return results; }
javascript
{ "resource": "" }
q19930
train
function(containerEl, attributeVal) { var AUTO_FOCUS = this.prefixer('md-autofocus', true); var elToFocus; elToFocus = scanForFocusable(containerEl, attributeVal || AUTO_FOCUS); if (!elToFocus && attributeVal != AUTO_FOCUS) { // Scan for deprecated attribute elToFocus = scanForFocusable(containerEl, this.prefixer('md-auto-focus', true)); if (!elToFocus) { // Scan for fallback to 'universal' API elToFocus = scanForFocusable(containerEl, AUTO_FOCUS); } } return elToFocus; /** * Can target and nested children for specified Selector (attribute) * whose value may be an expression that evaluates to True/False. */ function scanForFocusable(target, selector) { var elFound, items = target[0].querySelectorAll(selector); // Find the last child element with the focus attribute if (items && items.length){ items.length && angular.forEach(items, function(it) { it = angular.element(it); // Check the element for the md-autofocus class to ensure any associated expression // evaluated to true. var isFocusable = it.hasClass('md-autofocus'); if (isFocusable) elFound = it; }); } return elFound; } }
javascript
{ "resource": "" }
q19931
disableElementScroll
train
function disableElementScroll(element) { element = angular.element(element || body); var scrollMask; if (options.disableScrollMask) { scrollMask = element; } else { scrollMask = angular.element( '<div class="md-scroll-mask">' + ' <div class="md-scroll-mask-bar"></div>' + '</div>'); element.append(scrollMask); } scrollMask.on('wheel', preventDefault); scrollMask.on('touchmove', preventDefault); return function restoreElementScroll() { scrollMask.off('wheel'); scrollMask.off('touchmove'); if (!options.disableScrollMask && scrollMask[0].parentNode) { scrollMask[0].parentNode.removeChild(scrollMask[0]); } }; function preventDefault(e) { e.preventDefault(); } }
javascript
{ "resource": "" }
q19932
disableBodyScroll
train
function disableBodyScroll() { var documentElement = $document[0].documentElement; var prevDocumentStyle = documentElement.style.cssText || ''; var prevBodyStyle = body.style.cssText || ''; var viewportTop = $mdUtil.getViewportTop(); $mdUtil.disableScrollAround._viewPortTop = viewportTop; var clientWidth = body.clientWidth; var hasVerticalScrollbar = body.scrollHeight > body.clientHeight + 1; // Scroll may be set on <html> element (for example by overflow-y: scroll) // but Chrome is reporting the scrollTop position always on <body>. // scrollElement will allow to restore the scrollTop position to proper target. var scrollElement = documentElement.scrollTop > 0 ? documentElement : body; if (hasVerticalScrollbar) { angular.element(body).css({ position: 'fixed', width: '100%', top: -viewportTop + 'px' }); } if (body.clientWidth < clientWidth) { body.style.overflow = 'hidden'; } return function restoreScroll() { // Reset the inline style CSS to the previous. body.style.cssText = prevBodyStyle; documentElement.style.cssText = prevDocumentStyle; // The scroll position while being fixed scrollElement.scrollTop = viewportTop; }; }
javascript
{ "resource": "" }
q19933
train
function(element) { var node = element[0] || element; document.addEventListener('click', function focusOnClick(ev) { if (ev.target === node && ev.$focus) { node.focus(); ev.stopImmediatePropagation(); ev.preventDefault(); node.removeEventListener('click', focusOnClick); } }, true); var newEvent = document.createEvent('MouseEvents'); newEvent.initMouseEvent('click', false, true, window, {}, 0, 0, 0, 0, false, false, false, false, 0, null); newEvent.$material = true; newEvent.$focus = true; node.dispatchEvent(newEvent); }
javascript
{ "resource": "" }
q19934
throttle
train
function throttle(func, delay) { var recent; return function throttled() { var context = this; var args = arguments; var now = $mdUtil.now(); if (!recent || (now - recent > delay)) { func.apply(context, args); recent = now; } }; }
javascript
{ "resource": "" }
q19935
reconnectScope
train
function reconnectScope(scope) { if (!scope) return; // we can't disconnect the root node or scope already disconnected if (scope.$root === scope) return; if (!scope.$$disconnected) return; var child = scope; var parent = child.$parent; child.$$disconnected = false; // See Scope.$new for this logic... child.$$prevSibling = parent.$$childTail; if (parent.$$childHead) { parent.$$childTail.$$nextSibling = child; parent.$$childTail = child; } else { parent.$$childHead = parent.$$childTail = child; } }
javascript
{ "resource": "" }
q19936
scanChildren
train
function scanChildren(element) { var found; if (element) { for (var i = 0, len = element.length; i < len; i++) { var target = element[i]; if (!found) { for (var j = 0, numChild = target.childNodes.length; j < numChild; j++) { found = found || scanTree([target.childNodes[j]]); } } } } return found; }
javascript
{ "resource": "" }
q19937
train
function(scope, attr, defaults) { defaults = defaults || {}; angular.forEach(scope.$$isolateBindings, function(binding, key) { if (binding.optional && angular.isUndefined(scope[key])) { var attrIsDefined = angular.isDefined(attr[binding.attrName]); scope[key] = angular.isDefined(defaults[key]) ? defaults[key] : attrIsDefined; } }); }
javascript
{ "resource": "" }
q19938
processQueue
train
function processQueue() { var queue = nextTick.queue; var digest = nextTick.digest; nextTick.queue = []; nextTick.timeout = null; nextTick.digest = false; queue.forEach(function(queueItem) { var skip = queueItem.scope && queueItem.scope.$$destroyed; if (!skip) { queueItem.callback(); } }); if (digest) $rootScope.$digest(); }
javascript
{ "resource": "" }
q19939
train
function (element) { var parent = element.parent(); // jqLite might return a non-null, but still empty, parent; so check for parent and length while (hasComputedStyle(parent, 'pointer-events', 'none')) { parent = parent.parent(); } return parent; }
javascript
{ "resource": "" }
q19940
train
function() { var stickyProp; var testEl = angular.element('<div>'); $document[0].body.appendChild(testEl[0]); var stickyProps = ['sticky', '-webkit-sticky']; for (var i = 0; i < stickyProps.length; ++i) { testEl.css({ position: stickyProps[i], top: 0, 'z-index': 2 }); if (testEl.css('position') == stickyProps[i]) { stickyProp = stickyProps[i]; break; } } testEl.remove(); return stickyProp; }
javascript
{ "resource": "" }
q19941
train
function(element) { var parent = $mdUtil.getClosest(element, 'form'); var form = parent ? angular.element(parent).controller('form') : null; return form ? form.$submitted : false; }
javascript
{ "resource": "" }
q19942
train
function(element, scrollEnd, duration) { var scrollStart = element.scrollTop; var scrollChange = scrollEnd - scrollStart; var scrollingDown = scrollStart < scrollEnd; var startTime = $mdUtil.now(); $$rAF(scrollChunk); function scrollChunk() { var newPosition = calculateNewPosition(); element.scrollTop = newPosition; if (scrollingDown ? newPosition < scrollEnd : newPosition > scrollEnd) { $$rAF(scrollChunk); } } function calculateNewPosition() { var easeDuration = duration || 1000; var currentTime = $mdUtil.now() - startTime; return ease(currentTime, scrollStart, scrollChange, easeDuration); } function ease(currentTime, start, change, duration) { // If the duration has passed (which can occur if our app loses focus due to $$rAF), jump // straight to the proper position if (currentTime > duration) { return start + change; } var ts = (currentTime /= duration) * currentTime; var tc = ts * currentTime; return start + change * (-2 * tc + 3 * ts); } }
javascript
{ "resource": "" }
q19943
train
function(array) { if (!array) { return; } return array.filter(function(value, index, self) { return self.indexOf(value) === index; }); }
javascript
{ "resource": "" }
q19944
train
function(element) { // For SVG or Symbol elements, innerHTML returns `undefined` in IE. // Reference: https://stackoverflow.com/q/28129956/633107 // The XMLSerializer API is supported on IE11 and is the recommended workaround. var serializer = new XMLSerializer(); return Array.prototype.map.call(element.childNodes, function (child) { return serializer.serializeToString(child); }).join(''); }
javascript
{ "resource": "" }
q19945
fakeItemMatch
train
function fakeItemMatch() { var matches = []; for (var i = 0; i < dropdownItems; i++) { matches.push('Item ' + i); } return matches; }
javascript
{ "resource": "" }
q19946
calculateInputValueLength
train
function calculateInputValueLength(value) { value = ngTrim && !isPasswordInput && angular.isString(value) ? value.trim() : value; if (value === undefined || value === null) { value = ''; } return String(value).length; }
javascript
{ "resource": "" }
q19947
calendarDirective
train
function calendarDirective() { return { template: '<div class="md-calendar-scroll-mask">' + '<md-virtual-repeat-container class="md-calendar-scroll-container">' + '<table role="grid" tabindex="0" class="md-calendar" aria-readonly="true">' + '<tbody ' + 'md-calendar-year-body ' + 'role="rowgroup" ' + 'md-virtual-repeat="i in yearCtrl.items" ' + 'md-year-offset="$index" class="md-calendar-year" ' + 'md-start-index="yearCtrl.getFocusedYearIndex()" ' + 'md-item-size="' + TBODY_HEIGHT + '">' + // The <tr> ensures that the <tbody> will have the proper // height, even though it may be empty. '<tr aria-hidden="true" md-force-height="\'' + TBODY_HEIGHT + 'px\'"></tr>' + '</tbody>' + '</table>' + '</md-virtual-repeat-container>' + '</div>', require: ['^^mdCalendar', 'mdCalendarYear'], controller: CalendarYearCtrl, controllerAs: 'yearCtrl', bindToController: true, link: function(scope, element, attrs, controllers) { var calendarCtrl = controllers[0]; var yearCtrl = controllers[1]; yearCtrl.initialize(calendarCtrl); } }; }
javascript
{ "resource": "" }
q19948
definePreset
train
function definePreset(name, preset) { if (!name || !preset) { throw new Error('mdPanelProvider: The panel preset definition is ' + 'malformed. The name and preset object are required.'); } else if (_presets.hasOwnProperty(name)) { throw new Error('mdPanelProvider: The panel preset you have requested ' + 'has already been defined.'); } // Delete any property on the preset that is not allowed. delete preset.id; delete preset.position; delete preset.animation; _presets[name] = preset; }
javascript
{ "resource": "" }
q19949
getComputedTranslations
train
function getComputedTranslations(el, property) { // The transform being returned by `getComputedStyle` is in the format: // `matrix(a, b, c, d, translateX, translateY)` if defined and `none` // if the element doesn't have a transform. var transform = getComputedStyle(el[0] || el)[property]; var openIndex = transform.indexOf('('); var closeIndex = transform.lastIndexOf(')'); var output = { x: 0, y: 0 }; if (openIndex > -1 && closeIndex > -1) { var parsedValues = transform .substring(openIndex + 1, closeIndex) .split(', ') .slice(-2); output.x = parseInt(parsedValues[0]); output.y = parseInt(parsedValues[1]); } return output; }
javascript
{ "resource": "" }
q19950
createContentURL
train
function createContentURL() { var path = ''; var name = element.text(); // Use $window.location.pathname to get the path with the baseURL included. // $location.path() does not include the baseURL. This is important to support how the docs // are deployed with baseURLs like /latest, /HEAD, /1.1.13, etc. if (scope.$root.$window && scope.$root.$window.location) { path = scope.$root.$window.location.pathname; } name = name .trim() // Trim text due to browsers extra whitespace. .replace(/'/g, '') // Transform apostrophes words to a single one. .replace(unsafeCharRegex, '-') // Replace unsafe chars with a dash symbol. .replace(/-{2,}/g, '-') // Remove repeating dash symbols. .replace(/^-|-$/g, '') // Remove preceding or ending dashes. .toLowerCase(); // Link should be lower-case for accessible URL. scope.name = name; scope.href = path + '#' + name; }
javascript
{ "resource": "" }
q19951
watchVariable
train
function watchVariable(variable, alias) { newScope[alias] = scope[variable]; scope.$watch(variable, function(value) { $mdUtil.nextTick(function() { newScope[alias] = value; }); }); }
javascript
{ "resource": "" }
q19952
buildCloakInterceptor
train
function buildCloakInterceptor(className) { return ['$timeout', function($timeout){ return { restrict : 'A', priority : -10, // run after normal ng-cloak compile : function(element) { if (!config.enabled) return angular.noop; // Re-add the cloak element.addClass(className); return function(scope, element) { // Wait while layout injectors configure, then uncloak // NOTE: $rAF does not delay enough... and this is a 1x-only event, // $timeout is acceptable. $timeout(function(){ element.removeClass(className); }, 10, false); }; } }; }]; }
javascript
{ "resource": "" }
q19953
train
function(element) { if (!config.enabled) return angular.noop; // Re-add the cloak element.addClass(className); return function(scope, element) { // Wait while layout injectors configure, then uncloak // NOTE: $rAF does not delay enough... and this is a 1x-only event, // $timeout is acceptable. $timeout(function(){ element.removeClass(className); }, 10, false); }; }
javascript
{ "resource": "" }
q19954
updateClassWithValue
train
function updateClassWithValue(element, className) { var lastClass; return function updateClassFn(newValue) { var value = validateAttributeValue(className, newValue || ""); if (angular.isDefined(value)) { if (lastClass) element.removeClass(lastClass); lastClass = !value ? className : className + "-" + value.trim().replace(WHITESPACE, "-"); element.addClass(lastClass); } }; }
javascript
{ "resource": "" }
q19955
warnAttrNotSupported
train
function warnAttrNotSupported(className) { var parts = className.split("-"); return ["$log", function($log) { $log.warn(className + "has been deprecated. Please use a `" + parts[0] + "-gt-<xxx>` variant."); return angular.noop; }]; }
javascript
{ "resource": "" }
q19956
validateAttributeValue
train
function validateAttributeValue(className, value, updateFn) { var origValue; if (!needsInterpolation(value)) { switch (className.replace(SUFFIXES,"")) { case 'layout' : if (!findIn(value, LAYOUT_OPTIONS)) { value = LAYOUT_OPTIONS[0]; // 'row'; } break; case 'flex' : if (!findIn(value, FLEX_OPTIONS)) { if (isNaN(value)) { value = ''; } } break; case 'flex-offset' : case 'flex-order' : if (!value || isNaN(+value)) { value = '0'; } break; case 'layout-align' : var axis = extractAlignAxis(value); value = $mdUtil.supplant("{main}-{cross}",axis); break; case 'layout-padding' : case 'layout-margin' : case 'layout-fill' : case 'layout-wrap' : case 'layout-nowrap' : value = ''; break; } if (value != origValue) { (updateFn || angular.noop)(value); } } return value ? value.trim() : ""; }
javascript
{ "resource": "" }
q19957
buildUpdateFn
train
function buildUpdateFn(element, className, attrs) { return function updateAttrValue(fallback) { if (!needsInterpolation(fallback)) { // Do not modify the element's attribute value; so // uses '<ui-layout layout="/api/sidebar.html" />' will not // be affected. Just update the attrs value. attrs[attrs.$normalize(className)] = fallback; } }; }
javascript
{ "resource": "" }
q19958
positionToPercent
train
function positionToPercent(position) { var offset = vertical ? sliderDimensions.top : sliderDimensions.left; var size = vertical ? sliderDimensions.height : sliderDimensions.width; var calc = (position - offset) / size; if (!vertical && $mdUtil.bidi() === 'rtl') { calc = 1 - calc; } return Math.max(0, Math.min(1, vertical ? 1 - calc : calc)); }
javascript
{ "resource": "" }
q19959
percentToValue
train
function percentToValue(percent) { var adjustedPercent = invert ? (1 - percent) : percent; return (min + adjustedPercent * (max - min)); }
javascript
{ "resource": "" }
q19960
expect
train
function expect(element, attrName, defaultValue) { var node = angular.element(element)[0] || element; // if node exists and neither it nor its children have the attribute if (node && ((!node.hasAttribute(attrName) || node.getAttribute(attrName).length === 0) && !childHasAttribute(node, attrName))) { defaultValue = angular.isString(defaultValue) ? defaultValue.trim() : ''; if (defaultValue.length) { element.attr(attrName, defaultValue); } else if (showWarnings) { $log.warn('ARIA: Attribute "', attrName, '", required for accessibility, is missing on node:', node); } } }
javascript
{ "resource": "" }
q19961
hasAriaLabel
train
function hasAriaLabel(element) { var node = angular.element(element)[0] || element; /* Check if compatible node type (ie: not HTML Document node) */ if (!node.hasAttribute) { return false; } /* Check label or description attributes */ return node.hasAttribute('aria-label') || node.hasAttribute('aria-labelledby') || node.hasAttribute('aria-describedby'); }
javascript
{ "resource": "" }
q19962
parentHasAriaLabel
train
function parentHasAriaLabel(element, level) { level = level || 1; var node = angular.element(element)[0] || element; if (!node.parentNode) { return false; } if (performCheck(node.parentNode)) { return true; } level--; if (level) { return parentHasAriaLabel(node.parentNode, level); } return false; function performCheck(parentNode) { if (!hasAriaLabel(parentNode)) { return false; } /* Perform role blacklist check */ if (parentNode.hasAttribute('role')) { switch (parentNode.getAttribute('role').toLowerCase()) { case 'command': case 'definition': case 'directory': case 'grid': case 'list': case 'listitem': case 'log': case 'marquee': case 'menu': case 'menubar': case 'note': case 'presentation': case 'separator': case 'scrollbar': case 'status': case 'tablist': return false; } } /* Perform tagName blacklist check */ switch (parentNode.tagName.toLowerCase()) { case 'abbr': case 'acronym': case 'address': case 'applet': case 'audio': case 'b': case 'bdi': case 'bdo': case 'big': case 'blockquote': case 'br': case 'canvas': case 'caption': case 'center': case 'cite': case 'code': case 'col': case 'data': case 'dd': case 'del': case 'dfn': case 'dir': case 'div': case 'dl': case 'em': case 'embed': case 'fieldset': case 'figcaption': case 'font': case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': case 'hgroup': case 'html': case 'i': case 'ins': case 'isindex': case 'kbd': case 'keygen': case 'label': case 'legend': case 'li': case 'map': case 'mark': case 'menu': case 'object': case 'ol': case 'output': case 'pre': case 'presentation': case 'q': case 'rt': case 'ruby': case 'samp': case 'small': case 'source': case 'span': case 'status': case 'strike': case 'strong': case 'sub': case 'sup': case 'svg': case 'tbody': case 'td': case 'th': case 'thead': case 'time': case 'tr': case 'track': case 'tt': case 'ul': case 'var': return false; } return true; } }
javascript
{ "resource": "" }
q19963
updateExpression
train
function updateExpression(value) { // Rather than passing undefined to the jqLite toggle class function we explicitly set the // value to true. Otherwise the class will be just toggled instead of being forced. if (angular.isUndefined(value)) { value = true; } element.toggleClass('md-autofocus', !!value); }
javascript
{ "resource": "" }
q19964
buildScanner
train
function buildScanner(pattern) { return function findPatternIn(content) { let dependencies; const match = pattern.exec(content || ''); const moduleName = match ? match[1].replace(/'/gi,'') : null; const depsMatch = match && match[2] && match[2].trim(); if (depsMatch) { dependencies = depsMatch.split(/\s*,\s*/).map(function(dep) { dep = dep.trim().slice(1, -1); // remove quotes return dep; }); } return match ? { name : moduleName || '', module : moduleName || '', dependencies : dependencies || [] } : null; }; }
javascript
{ "resource": "" }
q19965
getDashLength
train
function getDashLength(diameter, strokeWidth, value, limit) { return (diameter - strokeWidth) * $window.Math.PI * ((3 * (limit || 100) / 100) - (value/100)); }
javascript
{ "resource": "" }
q19966
MdTooltipRegistry
train
function MdTooltipRegistry() { var listeners = {}; var ngWindow = angular.element(window); return { register: register, deregister: deregister }; /** * Global event handler that dispatches the registered handlers in the * service. * @param {!Event} event Event object passed in by the browser */ function globalEventHandler(event) { if (listeners[event.type]) { listeners[event.type].forEach(function(currentHandler) { currentHandler.call(this, event); }, this); } } /** * Registers a new handler with the service. * @param {string} type Type of event to be registered. * @param {!Function} handler Event handler. * @param {boolean} useCapture Whether to use event capturing. */ function register(type, handler, useCapture) { var handlers = listeners[type] = listeners[type] || []; if (!handlers.length) { useCapture ? window.addEventListener(type, globalEventHandler, true) : ngWindow.on(type, globalEventHandler); } if (handlers.indexOf(handler) === -1) { handlers.push(handler); } } /** * Removes an event handler from the service. * @param {string} type Type of event handler. * @param {!Function} handler The event handler itself. * @param {boolean} useCapture Whether the event handler used event capturing. */ function deregister(type, handler, useCapture) { var handlers = listeners[type]; var index = handlers ? handlers.indexOf(handler) : -1; if (index > -1) { handlers.splice(index, 1); if (handlers.length === 0) { useCapture ? window.removeEventListener(type, globalEventHandler, true) : ngWindow.off(type, globalEventHandler); } } } }
javascript
{ "resource": "" }
q19967
globalEventHandler
train
function globalEventHandler(event) { if (listeners[event.type]) { listeners[event.type].forEach(function(currentHandler) { currentHandler.call(this, event); }, this); } }
javascript
{ "resource": "" }
q19968
register
train
function register(type, handler, useCapture) { var handlers = listeners[type] = listeners[type] || []; if (!handlers.length) { useCapture ? window.addEventListener(type, globalEventHandler, true) : ngWindow.on(type, globalEventHandler); } if (handlers.indexOf(handler) === -1) { handlers.push(handler); } }
javascript
{ "resource": "" }
q19969
deregister
train
function deregister(type, handler, useCapture) { var handlers = listeners[type]; var index = handlers ? handlers.indexOf(handler) : -1; if (index > -1) { handlers.splice(index, 1); if (handlers.length === 0) { useCapture ? window.removeEventListener(type, globalEventHandler, true) : ngWindow.off(type, globalEventHandler); } } }
javascript
{ "resource": "" }
q19970
findCellByLabel
train
function findCellByLabel(monthElement, day) { var tds = monthElement.querySelectorAll('td'); var td; for (var i = 0; i < tds.length; i++) { td = tds[i]; if (td.textContent === day.toString()) { return td; } } }
javascript
{ "resource": "" }
q19971
findMonthElement
train
function findMonthElement(element, date) { var months = element.querySelectorAll('[md-calendar-month-body]'); var monthHeader = dateLocale.monthHeaderFormatter(date); var month; for (var i = 0; i < months.length; i++) { month = months[i]; if (month.querySelector('tr:first-child td:first-child').textContent === monthHeader) { return month; } } return null; }
javascript
{ "resource": "" }
q19972
findYearElement
train
function findYearElement(parent, year) { var node = parent[0] || parent; var years = node.querySelectorAll('[md-calendar-year-body]'); var yearHeader = year.toString(); var target; for (var i = 0; i < years.length; i++) { target = years[i]; if (target.querySelector('.md-calendar-month-label').textContent === yearHeader) { return target; } } return null; }
javascript
{ "resource": "" }
q19973
createElement
train
function createElement(parentScope, templateOverride) { var directiveScope = parentScope || $rootScope.$new(); var template = templateOverride || '<md-calendar md-min-date="minDate" md-max-date="maxDate" ' + 'ng-model="myDate"></md-calendar>'; var attachedElement = angular.element(template); document.body.appendChild(attachedElement[0]); var newElement = $compile(attachedElement)(directiveScope); attachedCalendarElements.push(newElement); applyDateChange(); return newElement; }
javascript
{ "resource": "" }
q19974
dispatchKeyEvent
train
function dispatchKeyEvent(keyCode, opt_modifiers) { var mod = opt_modifiers || {}; angular.element(element).triggerHandler({ type: 'keydown', keyCode: keyCode, which: keyCode, ctrlKey: mod.ctrl, altKey: mod.alt, metaKey: mod.meta, shortKey: mod.shift }); }
javascript
{ "resource": "" }
q19975
decreasePageOffset
train
function decreasePageOffset(elements, currentOffset) { var canvas = elements.canvas, tabOffsets = getTabOffsets(elements), i, firstVisibleTabOffset; // Find the first fully visible tab in offset range for (i = 0; i < tabOffsets.length; i++) { if (tabOffsets[i] >= currentOffset) { firstVisibleTabOffset = tabOffsets[i]; break; } } // Return (the first visible tab offset - the tabs container width) without going negative return Math.max(0, firstVisibleTabOffset - canvas.clientWidth); }
javascript
{ "resource": "" }
q19976
increasePageOffset
train
function increasePageOffset(elements, currentOffset) { var canvas = elements.canvas, maxOffset = getTotalTabsWidth(elements) - canvas.clientWidth, tabOffsets = getTabOffsets(elements), i, firstHiddenTabOffset; // Find the first partially (or fully) invisible tab for (i = 0; i < tabOffsets.length, tabOffsets[i] <= currentOffset + canvas.clientWidth; i++) { firstHiddenTabOffset = tabOffsets[i]; } // Return the offset of the first hidden tab, or the maximum offset (whichever is smaller) return Math.min(maxOffset, firstHiddenTabOffset); }
javascript
{ "resource": "" }
q19977
getTabOffsets
train
function getTabOffsets(elements) { var i, tab, currentOffset = 0, offsets = []; for (i = 0; i < elements.tabs.length; i++) { tab = elements.tabs[i]; offsets.push(currentOffset); currentOffset += tab.offsetWidth; } return offsets; }
javascript
{ "resource": "" }
q19978
getTotalTabsWidth
train
function getTotalTabsWidth(elements) { var sum = 0, i, tab; for (i = 0; i < elements.tabs.length; i++) { tab = elements.tabs[i]; sum += tab.offsetWidth; } return sum; }
javascript
{ "resource": "" }
q19979
train
function() { return angular.extend({ }, themeConfig, { defaultTheme : defaultTheme, alwaysWatchTheme : alwaysWatchTheme, registeredStyles : [].concat(themeConfig.registeredStyles) }); }
javascript
{ "resource": "" }
q19980
checkPaletteValid
train
function checkPaletteValid(name, map) { var missingColors = VALID_HUE_VALUES.filter(function(field) { return !map[field]; }); if (missingColors.length) { throw new Error("Missing colors %1 in palette %2!" .replace('%1', missingColors.join(', ')) .replace('%2', name)); } return map; }
javascript
{ "resource": "" }
q19981
train
function (scope, el) { if (el === undefined) { el = scope; scope = undefined; } if (scope === undefined) { scope = $rootScope; } applyTheme.inherit(el, el); }
javascript
{ "resource": "" }
q19982
registered
train
function registered(themeName) { if (themeName === undefined || themeName === '') return true; return applyTheme.THEMES[themeName] !== undefined; }
javascript
{ "resource": "" }
q19983
inheritTheme
train
function inheritTheme (el, parent) { var ctrl = parent.controller('mdTheme') || el.data('$mdThemeController'); var scope = el.scope(); updateThemeClass(lookupThemeName()); if (ctrl) { var watchTheme = alwaysWatchTheme || ctrl.$shouldWatch || $mdUtil.parseAttributeBoolean(el.attr('md-theme-watch')); if (watchTheme || ctrl.isAsyncTheme) { var clearNameWatcher = function () { if (unwatch) { unwatch(); unwatch = undefined; } }; var unwatch = ctrl.registerChanges(function(name) { updateThemeClass(name); if (!watchTheme) { clearNameWatcher(); } }); if (scope) { scope.$on('$destroy', clearNameWatcher); } else { el.on('$destroy', clearNameWatcher); } } } /** * Find the theme name from the parent controller or element data */ function lookupThemeName() { // As a few components (dialog) add their controllers later, we should also watch for a controller init. return ctrl && ctrl.$mdTheme || (defaultTheme === 'default' ? '' : defaultTheme); } /** * Remove old theme class and apply a new one * NOTE: if not a valid theme name, then the current name is not changed */ function updateThemeClass(theme) { if (!theme) return; if (!registered(theme)) { $log.warn('Attempted to use unregistered theme \'' + theme + '\'. ' + 'Register it with $mdThemingProvider.theme().'); } var oldTheme = el.data('$mdThemeName'); if (oldTheme) el.removeClass('md-' + oldTheme +'-theme'); el.addClass('md-' + theme + '-theme'); el.data('$mdThemeName', theme); if (ctrl) { el.data('$mdThemeController', ctrl); } } }
javascript
{ "resource": "" }
q19984
init
train
function init () { $mdUtil.initOptionalProperties($scope, $attrs, { searchText: '', selectedItem: null, clearButton: false, disableVirtualRepeat: false, }); $mdTheming($element); configureWatchers(); $mdUtil.nextTick(function () { gatherElements(); moveDropdown(); // Forward all focus events to the input element when autofocus is enabled if ($scope.autofocus) { $element.on('focus', focusInputElement); } if ($scope.inputAriaDescribedBy) { elements.input.setAttribute('aria-describedby', $scope.inputAriaDescribedBy); } if (!$scope.floatingLabel) { if ($scope.inputAriaLabel) { elements.input.setAttribute('aria-label', $scope.inputAriaLabel); } else if ($scope.inputAriaLabelledBy) { elements.input.setAttribute('aria-labelledby', $scope.inputAriaLabelledBy); } else if ($scope.placeholder) { // If no aria-label or aria-labelledby references are defined, then just label using the // placeholder. elements.input.setAttribute('aria-label', $scope.placeholder); } } }); }
javascript
{ "resource": "" }
q19985
getVerticalOffset
train
function getVerticalOffset () { var offset = 0; var inputContainer = $element.find('md-input-container'); if (inputContainer.length) { var input = inputContainer.find('input'); offset = inputContainer.prop('offsetHeight'); offset -= input.prop('offsetTop'); offset -= input.prop('offsetHeight'); // add in the height left up top for the floating label text offset += inputContainer.prop('offsetTop'); } return offset; }
javascript
{ "resource": "" }
q19986
moveDropdown
train
function moveDropdown () { if (!elements.$.root.length) return; $mdTheming(elements.$.scrollContainer); elements.$.scrollContainer.detach(); elements.$.root.append(elements.$.scrollContainer); if ($animate.pin) $animate.pin(elements.$.scrollContainer, $rootElement); }
javascript
{ "resource": "" }
q19987
cleanup
train
function cleanup () { if (!ctrl.hidden) { $mdUtil.enableScrolling(); } angular.element($window).off('resize', debouncedOnResize); if (elements){ var items = ['ul', 'scroller', 'scrollContainer', 'input']; angular.forEach(items, function(key){ elements.$[key].remove(); }); } }
javascript
{ "resource": "" }
q19988
gatherSnapWrap
train
function gatherSnapWrap() { var element; var value; for (element = $element; element.length; element = element.parent()) { value = element.attr('md-autocomplete-snap'); if (angular.isDefined(value)) break; } if (element.length) { return { snap: element[0], wrap: (value.toLowerCase() === 'width') ? element[0] : $element.find('md-autocomplete-wrap')[0] }; } var wrap = $element.find('md-autocomplete-wrap')[0]; return { snap: wrap, wrap: wrap }; }
javascript
{ "resource": "" }
q19989
getAngularElements
train
function getAngularElements (elements) { var obj = {}; for (var key in elements) { if (elements.hasOwnProperty(key)) obj[ key ] = angular.element(elements[ key ]); } return obj; }
javascript
{ "resource": "" }
q19990
disableElementScrollEvents
train
function disableElementScrollEvents(element) { function preventDefault(e) { e.preventDefault(); } element.on('wheel', preventDefault); element.on('touchmove', preventDefault); return function() { element.off('wheel', preventDefault); element.off('touchmove', preventDefault); }; }
javascript
{ "resource": "" }
q19991
onListLeave
train
function onListLeave () { if (!hasFocus && !ctrl.hidden) elements.input.focus(); noBlur = false; ctrl.hidden = shouldHide(); }
javascript
{ "resource": "" }
q19992
unregisterSelectedItemWatcher
train
function unregisterSelectedItemWatcher (cb) { var i = selectedItemWatchers.indexOf(cb); if (i !== -1) { selectedItemWatchers.splice(i, 1); } }
javascript
{ "resource": "" }
q19993
doBlur
train
function doBlur(forceBlur) { if (forceBlur) { noBlur = false; hasFocus = false; } elements.input.blur(); }
javascript
{ "resource": "" }
q19994
focus
train
function focus($event) { hasFocus = true; if (isSearchable() && isMinLengthMet()) { handleQuery(); } ctrl.hidden = shouldHide(); evalAttr('ngFocus', { $event: $event }); }
javascript
{ "resource": "" }
q19995
getItemAsNameVal
train
function getItemAsNameVal (item) { if (!item) { return undefined; } var locals = {}; if (ctrl.itemName) { locals[ ctrl.itemName ] = item; } return locals; }
javascript
{ "resource": "" }
q19996
isSearchable
train
function isSearchable() { if (ctrl.loading && !hasMatches()) { // No query when query is in progress. return false; } else if (hasSelection()) { // No query if there is already a selection return false; } else if (!hasFocus) { // No query if the input does not have focus return false; } return true; }
javascript
{ "resource": "" }
q19997
select
train
function select (index) { // force form to update state for validation $mdUtil.nextTick(function () { getDisplayValue(ctrl.matches[ index ]).then(function (val) { var ngModel = elements.$.input.controller('ngModel'); $mdLiveAnnouncer.announce(val + ' ' + ctrl.selectedMessage, 'assertive'); ngModel.$setViewValue(val); ngModel.$render(); }).finally(function () { $scope.selectedItem = ctrl.matches[ index ]; setLoading(false); }); }, false); }
javascript
{ "resource": "" }
q19998
reportMessages
train
function reportMessages(isPolite, types) { var politeness = isPolite ? 'polite' : 'assertive'; var messages = []; if (types & ReportType.Selected && ctrl.index !== -1) { messages.push(getCurrentDisplayValue()); } if (types & ReportType.Count) { messages.push($q.resolve(getCountMessage())); } $q.all(messages).then(function(data) { $mdLiveAnnouncer.announce(data.join(' '), politeness); }); }
javascript
{ "resource": "" }
q19999
handleQuery
train
function handleQuery () { var searchText = $scope.searchText || ''; var term = searchText.toLowerCase(); // If caching is enabled and the current searchText is stored in the cache if (!$scope.noCache && cache[term]) { // The results should be handled as same as a normal un-cached request does. handleResults(cache[term]); } else { fetchResults(searchText); } ctrl.hidden = shouldHide(); }
javascript
{ "resource": "" }