angular-ui-bootstrap.js 120KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905
  1. /*
  2. * angular-ui-bootstrap
  3. * http://angular-ui.github.io/bootstrap/
  4. * Version: 0.13.0-SNAPSHOT - 2015-12-28
  5. * License: MIT
  6. */
  7. angular.module("ui.bootstrap", ["ui.bootstrap.transition","ui.bootstrap.collapse","ui.bootstrap.accordion","ui.bootstrap.alert","ui.bootstrap.bindHtml","ui.bootstrap.buttons","ui.bootstrap.carousel","ui.bootstrap.dateparser","ui.bootstrap.position","ui.bootstrap.datepicker","ui.bootstrap.dropdown","ui.bootstrap.modal","ui.bootstrap.pagination","ui.bootstrap.tooltip","ui.bootstrap.popover","ui.bootstrap.progressbar","ui.bootstrap.rating","ui.bootstrap.tabs","ui.bootstrap.timepicker","ui.bootstrap.typeahead"]);
  8. angular.module('ui.bootstrap.transition', [])
  9. /**
  10. * $transition service provides a consistent interface to trigger CSS 3 transitions and to be informed when they complete.
  11. * @param {DOMElement} element The DOMElement that will be animated.
  12. * @param {string|object|function} trigger The thing that will cause the transition to start:
  13. * - As a string, it represents the css class to be added to the element.
  14. * - As an object, it represents a hash of style attributes to be applied to the element.
  15. * - As a function, it represents a function to be called that will cause the transition to occur.
  16. * @return {Promise} A promise that is resolved when the transition finishes.
  17. */
  18. .factory('$transition', ['$q', '$timeout', '$rootScope', function($q, $timeout, $rootScope) {
  19. var $transition = function(element, trigger, options) {
  20. options = options || {};
  21. var deferred = $q.defer();
  22. var endEventName = $transition[options.animation ? 'animationEndEventName' : 'transitionEndEventName'];
  23. var transitionEndHandler = function(event) {
  24. $rootScope.$apply(function() {
  25. element.unbind(endEventName, transitionEndHandler);
  26. deferred.resolve(element);
  27. });
  28. };
  29. if (endEventName) {
  30. element.bind(endEventName, transitionEndHandler);
  31. }
  32. // Wrap in a timeout to allow the browser time to update the DOM before the transition is to occur
  33. $timeout(function() {
  34. if ( angular.isString(trigger) ) {
  35. element.addClass(trigger);
  36. } else if ( angular.isFunction(trigger) ) {
  37. trigger(element);
  38. } else if ( angular.isObject(trigger) ) {
  39. element.css(trigger);
  40. }
  41. //If browser does not support transitions, instantly resolve
  42. if ( !endEventName ) {
  43. deferred.resolve(element);
  44. }
  45. });
  46. // Add our custom cancel function to the promise that is returned
  47. // We can call this if we are about to run a new transition, which we know will prevent this transition from ending,
  48. // i.e. it will therefore never raise a transitionEnd event for that transition
  49. deferred.promise.cancel = function() {
  50. if ( endEventName ) {
  51. element.unbind(endEventName, transitionEndHandler);
  52. }
  53. deferred.reject('Transition cancelled');
  54. };
  55. return deferred.promise;
  56. };
  57. // Work out the name of the transitionEnd event
  58. var transElement = document.createElement('trans');
  59. var transitionEndEventNames = {
  60. 'WebkitTransition': 'webkitTransitionEnd',
  61. 'MozTransition': 'transitionend',
  62. 'OTransition': 'oTransitionEnd',
  63. 'transition': 'transitionend'
  64. };
  65. var animationEndEventNames = {
  66. 'WebkitTransition': 'webkitAnimationEnd',
  67. 'MozTransition': 'animationend',
  68. 'OTransition': 'oAnimationEnd',
  69. 'transition': 'animationend'
  70. };
  71. function findEndEventName(endEventNames) {
  72. for (var name in endEventNames){
  73. if (transElement.style[name] !== undefined) {
  74. return endEventNames[name];
  75. }
  76. }
  77. }
  78. $transition.transitionEndEventName = findEndEventName(transitionEndEventNames);
  79. $transition.animationEndEventName = findEndEventName(animationEndEventNames);
  80. return $transition;
  81. }]);
  82. angular.module('ui.bootstrap.collapse', ['ui.bootstrap.transition'])
  83. .directive('collapse', ['$transition', function ($transition) {
  84. return {
  85. link: function (scope, element, attrs) {
  86. var initialAnimSkip = true;
  87. var currentTransition;
  88. function doTransition(change) {
  89. var newTransition = $transition(element, change);
  90. if (currentTransition) {
  91. currentTransition.cancel();
  92. }
  93. currentTransition = newTransition;
  94. newTransition.then(newTransitionDone, newTransitionDone);
  95. return newTransition;
  96. function newTransitionDone() {
  97. // Make sure it's this transition, otherwise, leave it alone.
  98. if (currentTransition === newTransition) {
  99. currentTransition = undefined;
  100. }
  101. }
  102. }
  103. function expand() {
  104. if (initialAnimSkip) {
  105. initialAnimSkip = false;
  106. expandDone();
  107. } else {
  108. element.removeClass('collapse').addClass('collapsing');
  109. doTransition({ height: element[0].scrollHeight + 'px' }).then(expandDone);
  110. }
  111. }
  112. function expandDone() {
  113. element.removeClass('collapsing');
  114. element.addClass('collapse in');
  115. element.css({height: 'auto'});
  116. }
  117. function collapse() {
  118. if (initialAnimSkip) {
  119. initialAnimSkip = false;
  120. collapseDone();
  121. element.css({height: 0});
  122. } else {
  123. // CSS transitions don't work with height: auto, so we have to manually change the height to a specific value
  124. element.css({ height: element[0].scrollHeight + 'px' });
  125. //trigger reflow so a browser realizes that height was updated from auto to a specific value
  126. var x = element[0].offsetWidth;
  127. element.removeClass('collapse in').addClass('collapsing');
  128. doTransition({ height: 0 }).then(collapseDone);
  129. }
  130. }
  131. function collapseDone() {
  132. element.removeClass('collapsing');
  133. element.addClass('collapse');
  134. }
  135. scope.$watch(attrs.collapse, function (shouldCollapse) {
  136. if (shouldCollapse) {
  137. collapse();
  138. } else {
  139. expand();
  140. }
  141. });
  142. }
  143. };
  144. }]);
  145. angular.module('ui.bootstrap.accordion', ['ui.bootstrap.collapse'])
  146. .constant('accordionConfig', {
  147. closeOthers: true
  148. })
  149. .controller('AccordionController', ['$scope', '$attrs', 'accordionConfig', function ($scope, $attrs, accordionConfig) {
  150. // This array keeps track of the accordion groups
  151. this.groups = [];
  152. // Ensure that all the groups in this accordion are closed, unless close-others explicitly says not to
  153. this.closeOthers = function(openGroup) {
  154. var closeOthers = angular.isDefined($attrs.closeOthers) ? $scope.$eval($attrs.closeOthers) : accordionConfig.closeOthers;
  155. if ( closeOthers ) {
  156. angular.forEach(this.groups, function (group) {
  157. if ( group !== openGroup ) {
  158. group.isOpen = false;
  159. }
  160. });
  161. }
  162. };
  163. // This is called from the accordion-group directive to add itself to the accordion
  164. this.addGroup = function(groupScope) {
  165. var that = this;
  166. this.groups.push(groupScope);
  167. groupScope.$on('$destroy', function (event) {
  168. that.removeGroup(groupScope);
  169. });
  170. };
  171. // This is called from the accordion-group directive when to remove itself
  172. this.removeGroup = function(group) {
  173. var index = this.groups.indexOf(group);
  174. if ( index !== -1 ) {
  175. this.groups.splice(index, 1);
  176. }
  177. };
  178. }])
  179. // The accordion directive simply sets up the directive controller
  180. // and adds an accordion CSS class to itself element.
  181. .directive('accordion', function () {
  182. return {
  183. restrict:'EA',
  184. controller:'AccordionController',
  185. transclude: true,
  186. replace: false,
  187. templateUrl: 'template/accordion/accordion.html'
  188. };
  189. })
  190. // The accordion-group directive indicates a block of html that will expand and collapse in an accordion
  191. .directive('accordionGroup', function() {
  192. return {
  193. require:'^accordion', // We need this directive to be inside an accordion
  194. restrict:'EA',
  195. transclude:true, // It transcludes the contents of the directive into the template
  196. replace: true, // The element containing the directive will be replaced with the template
  197. templateUrl:'template/accordion/accordion-group.html',
  198. scope: {
  199. heading: '@', // Interpolate the heading attribute onto this scope
  200. isOpen: '=?',
  201. isDisabled: '=?'
  202. },
  203. controller: function() {
  204. this.setHeading = function(element) {
  205. this.heading = element;
  206. };
  207. },
  208. link: function(scope, element, attrs, accordionCtrl) {
  209. accordionCtrl.addGroup(scope);
  210. scope.$watch('isOpen', function(value) {
  211. if ( value ) {
  212. accordionCtrl.closeOthers(scope);
  213. }
  214. });
  215. scope.toggleOpen = function() {
  216. if ( !scope.isDisabled ) {
  217. scope.isOpen = !scope.isOpen;
  218. }
  219. };
  220. }
  221. };
  222. })
  223. // Use accordion-heading below an accordion-group to provide a heading containing HTML
  224. // <accordion-group>
  225. // <accordion-heading>Heading containing HTML - <img src="..."></accordion-heading>
  226. // </accordion-group>
  227. .directive('accordionHeading', function() {
  228. return {
  229. restrict: 'EA',
  230. transclude: true, // Grab the contents to be used as the heading
  231. template: '', // In effect remove this element!
  232. replace: true,
  233. require: '^accordionGroup',
  234. link: function(scope, element, attr, accordionGroupCtrl, transclude) {
  235. // Pass the heading to the accordion-group controller
  236. // so that it can be transcluded into the right place in the template
  237. // [The second parameter to transclude causes the elements to be cloned so that they work in ng-repeat]
  238. accordionGroupCtrl.setHeading(transclude(scope, function() {}));
  239. }
  240. };
  241. })
  242. // Use in the accordion-group template to indicate where you want the heading to be transcluded
  243. // You must provide the property on the accordion-group controller that will hold the transcluded element
  244. // <div class="accordion-group">
  245. // <div class="accordion-heading" ><a ... accordion-transclude="heading">...</a></div>
  246. // ...
  247. // </div>
  248. .directive('accordionTransclude', function() {
  249. return {
  250. require: '^accordionGroup',
  251. link: function(scope, element, attr, controller) {
  252. scope.$watch(function() { return controller[attr.accordionTransclude]; }, function(heading) {
  253. if ( heading ) {
  254. element.html('');
  255. element.append(heading);
  256. }
  257. });
  258. }
  259. };
  260. });
  261. angular.module('ui.bootstrap.alert', [])
  262. .controller('AlertController', ['$scope', '$attrs', function ($scope, $attrs) {
  263. $scope.closeable = 'close' in $attrs;
  264. this.close = $scope.close;
  265. }])
  266. .directive('alert', function () {
  267. return {
  268. restrict:'EA',
  269. controller:'AlertController',
  270. templateUrl:'template/alert/alert.html',
  271. transclude:true,
  272. replace:true,
  273. scope: {
  274. type: '@',
  275. close: '&'
  276. }
  277. };
  278. })
  279. .directive('dismissOnTimeout', ['$timeout', function($timeout) {
  280. return {
  281. require: 'alert',
  282. link: function(scope, element, attrs, alertCtrl) {
  283. $timeout(function(){
  284. alertCtrl.close();
  285. }, parseInt(attrs.dismissOnTimeout, 10));
  286. }
  287. };
  288. }]);
  289. angular.module('ui.bootstrap.bindHtml', [])
  290. .directive('bindHtmlUnsafe', function () {
  291. return function (scope, element, attr) {
  292. element.addClass('ng-binding').data('$binding', attr.bindHtmlUnsafe);
  293. scope.$watch(attr.bindHtmlUnsafe, function bindHtmlUnsafeWatchAction(value) {
  294. element.html(value || '');
  295. });
  296. };
  297. });
  298. angular.module('ui.bootstrap.buttons', [])
  299. .constant('buttonConfig', {
  300. activeClass: 'active',
  301. toggleEvent: 'click'
  302. })
  303. .controller('ButtonsController', ['buttonConfig', function(buttonConfig) {
  304. this.activeClass = buttonConfig.activeClass || 'active';
  305. this.toggleEvent = buttonConfig.toggleEvent || 'click';
  306. }])
  307. .directive('btnRadio', function () {
  308. return {
  309. require: ['btnRadio', 'ngModel'],
  310. controller: 'ButtonsController',
  311. link: function (scope, element, attrs, ctrls) {
  312. var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];
  313. //model -> UI
  314. ngModelCtrl.$render = function () {
  315. element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.btnRadio)));
  316. };
  317. //ui->model
  318. element.bind(buttonsCtrl.toggleEvent, function () {
  319. var isActive = element.hasClass(buttonsCtrl.activeClass);
  320. if (!isActive || angular.isDefined(attrs.uncheckable)) {
  321. scope.$apply(function () {
  322. ngModelCtrl.$setViewValue(isActive ? null : scope.$eval(attrs.btnRadio));
  323. ngModelCtrl.$render();
  324. });
  325. }
  326. });
  327. }
  328. };
  329. })
  330. .directive('btnCheckbox', function () {
  331. return {
  332. require: ['btnCheckbox', 'ngModel'],
  333. controller: 'ButtonsController',
  334. link: function (scope, element, attrs, ctrls) {
  335. var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];
  336. function getTrueValue() {
  337. return getCheckboxValue(attrs.btnCheckboxTrue, true);
  338. }
  339. function getFalseValue() {
  340. return getCheckboxValue(attrs.btnCheckboxFalse, false);
  341. }
  342. function getCheckboxValue(attributeValue, defaultValue) {
  343. var val = scope.$eval(attributeValue);
  344. return angular.isDefined(val) ? val : defaultValue;
  345. }
  346. //model -> UI
  347. ngModelCtrl.$render = function () {
  348. element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue()));
  349. };
  350. //ui->model
  351. element.bind(buttonsCtrl.toggleEvent, function () {
  352. scope.$apply(function () {
  353. ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue());
  354. ngModelCtrl.$render();
  355. });
  356. });
  357. }
  358. };
  359. });
  360. /**
  361. * @ngdoc overview
  362. * @name ui.bootstrap.carousel
  363. *
  364. * @description
  365. * AngularJS version of an image carousel.
  366. *
  367. */
  368. angular.module('ui.bootstrap.carousel', ['ui.bootstrap.transition'])
  369. .controller('CarouselController', ['$scope', '$timeout', '$interval', '$transition', function ($scope, $timeout, $interval, $transition) {
  370. var self = this,
  371. slides = self.slides = $scope.slides = [],
  372. currentIndex = -1,
  373. currentInterval, isPlaying;
  374. self.currentSlide = null;
  375. var destroyed = false;
  376. /* direction: "prev" or "next" */
  377. self.select = $scope.select = function(nextSlide, direction) {
  378. var nextIndex = slides.indexOf(nextSlide);
  379. //Decide direction if it's not given
  380. if (direction === undefined) {
  381. direction = nextIndex > currentIndex ? 'next' : 'prev';
  382. }
  383. if (nextSlide && nextSlide !== self.currentSlide) {
  384. if ($scope.$currentTransition) {
  385. $scope.$currentTransition.cancel();
  386. //Timeout so ng-class in template has time to fix classes for finished slide
  387. $timeout(goNext);
  388. } else {
  389. goNext();
  390. }
  391. }
  392. function goNext() {
  393. // Scope has been destroyed, stop here.
  394. if (destroyed) { return; }
  395. //If we have a slide to transition from and we have a transition type and we're allowed, go
  396. if (self.currentSlide && angular.isString(direction) && !$scope.noTransition && nextSlide.$element) {
  397. //We shouldn't do class manip in here, but it's the same weird thing bootstrap does. need to fix sometime
  398. nextSlide.$element.addClass(direction);
  399. var reflow = nextSlide.$element[0].offsetWidth; //force reflow
  400. //Set all other slides to stop doing their stuff for the new transition
  401. angular.forEach(slides, function(slide) {
  402. angular.extend(slide, {direction: '', entering: false, leaving: false, active: false});
  403. });
  404. angular.extend(nextSlide, {direction: direction, active: true, entering: true});
  405. angular.extend(self.currentSlide||{}, {direction: direction, leaving: true});
  406. $scope.$currentTransition = $transition(nextSlide.$element, {});
  407. //We have to create new pointers inside a closure since next & current will change
  408. (function(next,current) {
  409. $scope.$currentTransition.then(
  410. function(){ transitionDone(next, current); },
  411. function(){ transitionDone(next, current); }
  412. );
  413. }(nextSlide, self.currentSlide));
  414. } else {
  415. transitionDone(nextSlide, self.currentSlide);
  416. }
  417. self.currentSlide = nextSlide;
  418. currentIndex = nextIndex;
  419. //every time you change slides, reset the timer
  420. restartTimer();
  421. }
  422. function transitionDone(next, current) {
  423. angular.extend(next, {direction: '', active: true, leaving: false, entering: false});
  424. angular.extend(current||{}, {direction: '', active: false, leaving: false, entering: false});
  425. $scope.$currentTransition = null;
  426. }
  427. };
  428. $scope.$on('$destroy', function () {
  429. destroyed = true;
  430. });
  431. /* Allow outside people to call indexOf on slides array */
  432. self.indexOfSlide = function(slide) {
  433. return slides.indexOf(slide);
  434. };
  435. $scope.next = function() {
  436. var newIndex = (currentIndex + 1) % slides.length;
  437. //Prevent this user-triggered transition from occurring if there is already one in progress
  438. if (!$scope.$currentTransition) {
  439. return self.select(slides[newIndex], 'next');
  440. }
  441. };
  442. $scope.prev = function() {
  443. var newIndex = currentIndex - 1 < 0 ? slides.length - 1 : currentIndex - 1;
  444. //Prevent this user-triggered transition from occurring if there is already one in progress
  445. if (!$scope.$currentTransition) {
  446. return self.select(slides[newIndex], 'prev');
  447. }
  448. };
  449. $scope.isActive = function(slide) {
  450. return self.currentSlide === slide;
  451. };
  452. $scope.$watch('interval', restartTimer);
  453. $scope.$on('$destroy', resetTimer);
  454. function restartTimer() {
  455. resetTimer();
  456. var interval = +$scope.interval;
  457. if (!isNaN(interval) && interval > 0) {
  458. currentInterval = $interval(timerFn, interval);
  459. }
  460. }
  461. function resetTimer() {
  462. if (currentInterval) {
  463. $interval.cancel(currentInterval);
  464. currentInterval = null;
  465. }
  466. }
  467. function timerFn() {
  468. var interval = +$scope.interval;
  469. if (isPlaying && !isNaN(interval) && interval > 0) {
  470. $scope.next();
  471. } else {
  472. $scope.pause();
  473. }
  474. }
  475. $scope.play = function() {
  476. if (!isPlaying) {
  477. isPlaying = true;
  478. restartTimer();
  479. }
  480. };
  481. $scope.pause = function() {
  482. if (!$scope.noPause) {
  483. isPlaying = false;
  484. resetTimer();
  485. }
  486. };
  487. self.addSlide = function(slide, element) {
  488. slide.$element = element;
  489. slides.push(slide);
  490. //if this is the first slide or the slide is set to active, select it
  491. if(slides.length === 1 || slide.active) {
  492. self.select(slides[slides.length-1]);
  493. if (slides.length == 1) {
  494. $scope.play();
  495. }
  496. } else {
  497. slide.active = false;
  498. }
  499. };
  500. self.removeSlide = function(slide) {
  501. //get the index of the slide inside the carousel
  502. var index = slides.indexOf(slide);
  503. slides.splice(index, 1);
  504. if (slides.length > 0 && slide.active) {
  505. if (index >= slides.length) {
  506. self.select(slides[index-1]);
  507. } else {
  508. self.select(slides[index]);
  509. }
  510. } else if (currentIndex > index) {
  511. currentIndex--;
  512. }
  513. };
  514. }])
  515. /**
  516. * @ngdoc directive
  517. * @name ui.bootstrap.carousel.directive:carousel
  518. * @restrict EA
  519. *
  520. * @description
  521. * Carousel is the outer container for a set of image 'slides' to showcase.
  522. *
  523. * @param {number=} interval The time, in milliseconds, that it will take the carousel to go to the next slide.
  524. * @param {boolean=} noTransition Whether to disable transitions on the carousel.
  525. * @param {boolean=} noPause Whether to disable pausing on the carousel (by default, the carousel interval pauses on hover).
  526. *
  527. * @example
  528. <example module="ui.bootstrap">
  529. <file name="index.html">
  530. <carousel>
  531. <slide>
  532. <img src="http://placekitten.com/150/150" style="margin:auto;">
  533. <div class="carousel-caption">
  534. <p>Beautiful!</p>
  535. </div>
  536. </slide>
  537. <slide>
  538. <img src="http://placekitten.com/100/150" style="margin:auto;">
  539. <div class="carousel-caption">
  540. <p>D'aww!</p>
  541. </div>
  542. </slide>
  543. </carousel>
  544. </file>
  545. <file name="demo.css">
  546. .carousel-indicators {
  547. top: auto;
  548. bottom: 15px;
  549. }
  550. </file>
  551. </example>
  552. */
  553. .directive('carousel', [function() {
  554. return {
  555. restrict: 'EA',
  556. transclude: true,
  557. replace: true,
  558. controller: 'CarouselController',
  559. require: 'carousel',
  560. templateUrl: 'template/carousel/carousel.html',
  561. scope: {
  562. interval: '=',
  563. noTransition: '=',
  564. noPause: '='
  565. }
  566. };
  567. }])
  568. /**
  569. * @ngdoc directive
  570. * @name ui.bootstrap.carousel.directive:slide
  571. * @restrict EA
  572. *
  573. * @description
  574. * Creates a slide inside a {@link ui.bootstrap.carousel.directive:carousel carousel}. Must be placed as a child of a carousel element.
  575. *
  576. * @param {boolean=} active Model binding, whether or not this slide is currently active.
  577. *
  578. * @example
  579. <example module="ui.bootstrap">
  580. <file name="index.html">
  581. <div ng-controller="CarouselDemoCtrl">
  582. <carousel>
  583. <slide ng-repeat="slide in slides" active="slide.active">
  584. <img ng-src="{{slide.image}}" style="margin:auto;">
  585. <div class="carousel-caption">
  586. <h4>Slide {{$index}}</h4>
  587. <p>{{slide.text}}</p>
  588. </div>
  589. </slide>
  590. </carousel>
  591. Interval, in milliseconds: <input type="number" ng-model="myInterval">
  592. <br />Enter a negative number to stop the interval.
  593. </div>
  594. </file>
  595. <file name="script.js">
  596. function CarouselDemoCtrl($scope) {
  597. $scope.myInterval = 5000;
  598. }
  599. </file>
  600. <file name="demo.css">
  601. .carousel-indicators {
  602. top: auto;
  603. bottom: 15px;
  604. }
  605. </file>
  606. </example>
  607. */
  608. .directive('slide', function() {
  609. return {
  610. require: '^carousel',
  611. restrict: 'EA',
  612. transclude: true,
  613. replace: true,
  614. templateUrl: 'template/carousel/slide.html',
  615. scope: {
  616. active: '=?'
  617. },
  618. link: function (scope, element, attrs, carouselCtrl) {
  619. carouselCtrl.addSlide(scope, element);
  620. //when the scope is destroyed then remove the slide from the current slides array
  621. scope.$on('$destroy', function() {
  622. carouselCtrl.removeSlide(scope);
  623. });
  624. scope.$watch('active', function(active) {
  625. if (active) {
  626. carouselCtrl.select(scope);
  627. }
  628. });
  629. }
  630. };
  631. });
  632. angular.module('ui.bootstrap.dateparser', [])
  633. .service('dateParser', ['$locale', 'orderByFilter', function($locale, orderByFilter) {
  634. this.parsers = {};
  635. var formatCodeToRegex = {
  636. 'yyyy': {
  637. regex: '\\d{4}',
  638. apply: function(value) { this.year = +value; }
  639. },
  640. 'yy': {
  641. regex: '\\d{2}',
  642. apply: function(value) { this.year = +value + 2000; }
  643. },
  644. 'y': {
  645. regex: '\\d{1,4}',
  646. apply: function(value) { this.year = +value; }
  647. },
  648. 'MMMM': {
  649. regex: $locale.DATETIME_FORMATS.MONTH.join('|'),
  650. apply: function(value) { this.month = $locale.DATETIME_FORMATS.MONTH.indexOf(value); }
  651. },
  652. 'MMM': {
  653. regex: $locale.DATETIME_FORMATS.SHORTMONTH.join('|'),
  654. apply: function(value) { this.month = $locale.DATETIME_FORMATS.SHORTMONTH.indexOf(value); }
  655. },
  656. 'MM': {
  657. regex: '0[1-9]|1[0-2]',
  658. apply: function(value) { this.month = value - 1; }
  659. },
  660. 'M': {
  661. regex: '[1-9]|1[0-2]',
  662. apply: function(value) { this.month = value - 1; }
  663. },
  664. 'dd': {
  665. regex: '[0-2][0-9]{1}|3[0-1]{1}',
  666. apply: function(value) { this.date = +value; }
  667. },
  668. 'd': {
  669. regex: '[1-2]?[0-9]{1}|3[0-1]{1}',
  670. apply: function(value) { this.date = +value; }
  671. },
  672. 'EEEE': {
  673. regex: $locale.DATETIME_FORMATS.DAY.join('|')
  674. },
  675. 'EEE': {
  676. regex: $locale.DATETIME_FORMATS.SHORTDAY.join('|')
  677. }
  678. };
  679. function createParser(format) {
  680. var map = [], regex = format.split('');
  681. angular.forEach(formatCodeToRegex, function(data, code) {
  682. var index = format.indexOf(code);
  683. if (index > -1) {
  684. format = format.split('');
  685. regex[index] = '(' + data.regex + ')';
  686. format[index] = '$'; // Custom symbol to define consumed part of format
  687. for (var i = index + 1, n = index + code.length; i < n; i++) {
  688. regex[i] = '';
  689. format[i] = '$';
  690. }
  691. format = format.join('');
  692. map.push({ index: index, apply: data.apply });
  693. }
  694. });
  695. return {
  696. regex: new RegExp('^' + regex.join('') + '$'),
  697. map: orderByFilter(map, 'index')
  698. };
  699. }
  700. this.parse = function(input, format) {
  701. if ( !angular.isString(input) || !format ) {
  702. return input;
  703. }
  704. format = $locale.DATETIME_FORMATS[format] || format;
  705. if ( !this.parsers[format] ) {
  706. this.parsers[format] = createParser(format);
  707. }
  708. var parser = this.parsers[format],
  709. regex = parser.regex,
  710. map = parser.map,
  711. results = input.match(regex);
  712. if ( results && results.length ) {
  713. var fields = { year: 1900, month: 0, date: 1, hours: 0 }, dt;
  714. for( var i = 1, n = results.length; i < n; i++ ) {
  715. var mapper = map[i-1];
  716. if ( mapper.apply ) {
  717. mapper.apply.call(fields, results[i]);
  718. }
  719. }
  720. if ( isValid(fields.year, fields.month, fields.date) ) {
  721. dt = new Date( fields.year, fields.month, fields.date, fields.hours);
  722. }
  723. return dt;
  724. }
  725. };
  726. // Check if date is valid for specific month (and year for February).
  727. // Month: 0 = Jan, 1 = Feb, etc
  728. function isValid(year, month, date) {
  729. if ( month === 1 && date > 28) {
  730. return date === 29 && ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0);
  731. }
  732. if ( month === 3 || month === 5 || month === 8 || month === 10) {
  733. return date < 31;
  734. }
  735. return true;
  736. }
  737. }]);
  738. angular.module('ui.bootstrap.position', [])
  739. /**
  740. * A set of utility methods that can be use to retrieve position of DOM elements.
  741. * It is meant to be used where we need to absolute-position DOM elements in
  742. * relation to other, existing elements (this is the case for tooltips, popovers,
  743. * typeahead suggestions etc.).
  744. */
  745. .factory('$position', ['$document', '$window', function ($document, $window) {
  746. function getStyle(el, cssprop) {
  747. if (el.currentStyle) { //IE
  748. return el.currentStyle[cssprop];
  749. } else if ($window.getComputedStyle) {
  750. return $window.getComputedStyle(el)[cssprop];
  751. }
  752. // finally try and get inline style
  753. return el.style[cssprop];
  754. }
  755. /**
  756. * Checks if a given element is statically positioned
  757. * @param element - raw DOM element
  758. */
  759. function isStaticPositioned(element) {
  760. return (getStyle(element, 'position') || 'static' ) === 'static';
  761. }
  762. /**
  763. * returns the closest, non-statically positioned parentOffset of a given element
  764. * @param element
  765. */
  766. var parentOffsetEl = function (element) {
  767. var docDomEl = $document[0];
  768. var offsetParent = element.offsetParent || docDomEl;
  769. while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent) ) {
  770. offsetParent = offsetParent.offsetParent;
  771. }
  772. return offsetParent || docDomEl;
  773. };
  774. return {
  775. /**
  776. * Provides read-only equivalent of jQuery's position function:
  777. * http://api.jquery.com/position/
  778. */
  779. position: function (element) {
  780. var elBCR = this.offset(element);
  781. var offsetParentBCR = { top: 0, left: 0 };
  782. var offsetParentEl = parentOffsetEl(element[0]);
  783. if (offsetParentEl != $document[0]) {
  784. offsetParentBCR = this.offset(angular.element(offsetParentEl));
  785. offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop;
  786. offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft;
  787. }
  788. var boundingClientRect = element[0].getBoundingClientRect();
  789. return {
  790. width: boundingClientRect.width || element.prop('offsetWidth'),
  791. height: boundingClientRect.height || element.prop('offsetHeight'),
  792. top: elBCR.top - offsetParentBCR.top,
  793. left: elBCR.left - offsetParentBCR.left
  794. };
  795. },
  796. /**
  797. * Provides read-only equivalent of jQuery's offset function:
  798. * http://api.jquery.com/offset/
  799. */
  800. offset: function (element) {
  801. var boundingClientRect = element[0].getBoundingClientRect();
  802. return {
  803. width: boundingClientRect.width || element.prop('offsetWidth'),
  804. height: boundingClientRect.height || element.prop('offsetHeight'),
  805. top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop),
  806. left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft)
  807. };
  808. },
  809. /**
  810. * Provides coordinates for the targetEl in relation to hostEl
  811. */
  812. positionElements: function (hostEl, targetEl, positionStr, appendToBody) {
  813. var positionStrParts = positionStr.split('-');
  814. var pos0 = positionStrParts[0], pos1 = positionStrParts[1] || 'center';
  815. var hostElPos,
  816. targetElWidth,
  817. targetElHeight,
  818. targetElPos;
  819. hostElPos = appendToBody ? this.offset(hostEl) : this.position(hostEl);
  820. targetElWidth = targetEl.prop('offsetWidth');
  821. targetElHeight = targetEl.prop('offsetHeight');
  822. var shiftWidth = {
  823. center: function () {
  824. return hostElPos.left + hostElPos.width / 2 - targetElWidth / 2;
  825. },
  826. left: function () {
  827. return hostElPos.left;
  828. },
  829. right: function () {
  830. return hostElPos.left + hostElPos.width;
  831. }
  832. };
  833. var shiftHeight = {
  834. center: function () {
  835. return hostElPos.top + hostElPos.height / 2 - targetElHeight / 2;
  836. },
  837. top: function () {
  838. return hostElPos.top;
  839. },
  840. bottom: function () {
  841. return hostElPos.top + hostElPos.height;
  842. }
  843. };
  844. switch (pos0) {
  845. case 'right':
  846. targetElPos = {
  847. top: shiftHeight[pos1](),
  848. left: shiftWidth[pos0]()
  849. };
  850. break;
  851. case 'left':
  852. targetElPos = {
  853. top: shiftHeight[pos1](),
  854. left: hostElPos.left - targetElWidth
  855. };
  856. break;
  857. case 'bottom':
  858. targetElPos = {
  859. top: shiftHeight[pos0](),
  860. left: shiftWidth[pos1]()
  861. };
  862. break;
  863. default:
  864. targetElPos = {
  865. top: hostElPos.top - targetElHeight,
  866. left: shiftWidth[pos1]()
  867. };
  868. break;
  869. }
  870. return targetElPos;
  871. }
  872. };
  873. }]);
  874. angular.module('ui.bootstrap.datepicker', ['ui.bootstrap.dateparser', 'ui.bootstrap.position'])
  875. .constant('datepickerConfig', {
  876. formatDay: 'dd',
  877. formatMonth: 'MMMM',
  878. formatYear: 'yyyy',
  879. formatDayHeader: 'EEE',
  880. formatDayTitle: 'MMMM yyyy',
  881. formatMonthTitle: 'yyyy',
  882. datepickerMode: 'day',
  883. minMode: 'day',
  884. maxMode: 'year',
  885. showWeeks: true,
  886. startingDay: 0,
  887. yearRange: 20,
  888. minDate: null,
  889. maxDate: null
  890. })
  891. .controller('DatepickerController', ['$scope', '$attrs', '$parse', '$interpolate', '$timeout', '$log', 'dateFilter', 'datepickerConfig', function($scope, $attrs, $parse, $interpolate, $timeout, $log, dateFilter, datepickerConfig) {
  892. var self = this,
  893. ngModelCtrl = { $setViewValue: angular.noop }; // nullModelCtrl;
  894. // Modes chain
  895. this.modes = ['day', 'month', 'year'];
  896. // Configuration attributes
  897. angular.forEach(['formatDay', 'formatMonth', 'formatYear', 'formatDayHeader', 'formatDayTitle', 'formatMonthTitle',
  898. 'minMode', 'maxMode', 'showWeeks', 'startingDay', 'yearRange'], function( key, index ) {
  899. self[key] = angular.isDefined($attrs[key]) ? (index < 8 ? $interpolate($attrs[key])($scope.$parent) : $scope.$parent.$eval($attrs[key])) : datepickerConfig[key];
  900. });
  901. // Watchable date attributes
  902. angular.forEach(['minDate', 'maxDate'], function( key ) {
  903. if ( $attrs[key] ) {
  904. $scope.$parent.$watch($parse($attrs[key]), function(value) {
  905. self[key] = value ? new Date(value) : null;
  906. self.refreshView();
  907. });
  908. } else {
  909. self[key] = datepickerConfig[key] ? new Date(datepickerConfig[key]) : null;
  910. }
  911. });
  912. $scope.datepickerMode = $scope.datepickerMode || datepickerConfig.datepickerMode;
  913. $scope.uniqueId = 'datepicker-' + $scope.$id + '-' + Math.floor(Math.random() * 10000);
  914. this.activeDate = angular.isDefined($attrs.initDate) ? $scope.$parent.$eval($attrs.initDate) : new Date();
  915. $scope.isActive = function(dateObject) {
  916. if (self.compare(dateObject.date, self.activeDate) === 0) {
  917. $scope.activeDateId = dateObject.uid;
  918. return true;
  919. }
  920. return false;
  921. };
  922. this.init = function( ngModelCtrl_ ) {
  923. ngModelCtrl = ngModelCtrl_;
  924. ngModelCtrl.$render = function() {
  925. self.render();
  926. };
  927. };
  928. this.render = function() {
  929. if ( ngModelCtrl.$modelValue ) {
  930. var date = new Date( ngModelCtrl.$modelValue ),
  931. isValid = !isNaN(date);
  932. if ( isValid ) {
  933. this.activeDate = date;
  934. } else {
  935. $log.error('Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');
  936. }
  937. ngModelCtrl.$setValidity('date', isValid);
  938. }
  939. this.refreshView();
  940. };
  941. this.refreshView = function() {
  942. if ( this.element ) {
  943. this._refreshView();
  944. var date = ngModelCtrl.$modelValue ? new Date(ngModelCtrl.$modelValue) : null;
  945. ngModelCtrl.$setValidity('date-disabled', !date || (this.element && !this.isDisabled(date)));
  946. }
  947. };
  948. this.createDateObject = function(date, format) {
  949. var model = ngModelCtrl.$modelValue ? new Date(ngModelCtrl.$modelValue) : null;
  950. return {
  951. date: date,
  952. label: dateFilter(date, format),
  953. selected: model && this.compare(date, model) === 0,
  954. disabled: this.isDisabled(date),
  955. current: this.compare(date, new Date()) === 0
  956. };
  957. };
  958. this.isDisabled = function( date ) {
  959. return ((this.minDate && this.compare(date, this.minDate) < 0) || (this.maxDate && this.compare(date, this.maxDate) > 0) || ($attrs.dateDisabled && $scope.dateDisabled({date: date, mode: $scope.datepickerMode})));
  960. };
  961. // Split array into smaller arrays
  962. this.split = function(arr, size) {
  963. var arrays = [];
  964. while (arr.length > 0) {
  965. arrays.push(arr.splice(0, size));
  966. }
  967. return arrays;
  968. };
  969. $scope.select = function( date ) {
  970. if ( $scope.datepickerMode === self.minMode ) {
  971. var dt = ngModelCtrl.$modelValue ? new Date( ngModelCtrl.$modelValue ) : new Date(0, 0, 0, 0, 0, 0, 0);
  972. dt.setFullYear( date.getFullYear(), date.getMonth(), date.getDate() );
  973. ngModelCtrl.$setViewValue( dt );
  974. ngModelCtrl.$render();
  975. } else {
  976. self.activeDate = date;
  977. $scope.datepickerMode = self.modes[ self.modes.indexOf( $scope.datepickerMode ) - 1 ];
  978. }
  979. };
  980. $scope.move = function( direction ) {
  981. var year = self.activeDate.getFullYear() + direction * (self.step.years || 0),
  982. month = self.activeDate.getMonth() + direction * (self.step.months || 0);
  983. self.activeDate.setFullYear(year, month, 1);
  984. self.refreshView();
  985. };
  986. $scope.toggleMode = function( direction ) {
  987. direction = direction || 1;
  988. if (($scope.datepickerMode === self.maxMode && direction === 1) || ($scope.datepickerMode === self.minMode && direction === -1)) {
  989. return;
  990. }
  991. $scope.datepickerMode = self.modes[ self.modes.indexOf( $scope.datepickerMode ) + direction ];
  992. };
  993. // Key event mapper
  994. $scope.keys = { 13:'enter', 32:'space', 33:'pageup', 34:'pagedown', 35:'end', 36:'home', 37:'left', 38:'up', 39:'right', 40:'down' };
  995. var focusElement = function() {
  996. $timeout(function() {
  997. self.element[0].focus();
  998. }, 0 , false);
  999. };
  1000. // Listen for focus requests from popup directive
  1001. $scope.$on('datepicker.focus', focusElement);
  1002. $scope.keydown = function( evt ) {
  1003. var key = $scope.keys[evt.which];
  1004. if ( !key || evt.shiftKey || evt.altKey ) {
  1005. return;
  1006. }
  1007. evt.preventDefault();
  1008. evt.stopPropagation();
  1009. if (key === 'enter' || key === 'space') {
  1010. if ( self.isDisabled(self.activeDate)) {
  1011. return; // do nothing
  1012. }
  1013. $scope.select(self.activeDate);
  1014. focusElement();
  1015. } else if (evt.ctrlKey && (key === 'up' || key === 'down')) {
  1016. $scope.toggleMode(key === 'up' ? 1 : -1);
  1017. focusElement();
  1018. } else {
  1019. self.handleKeyDown(key, evt);
  1020. self.refreshView();
  1021. }
  1022. };
  1023. }])
  1024. .directive( 'datepicker', function () {
  1025. return {
  1026. restrict: 'EA',
  1027. replace: true,
  1028. templateUrl: 'template/datepicker/datepicker.html',
  1029. scope: {
  1030. datepickerMode: '=?',
  1031. dateDisabled: '&'
  1032. },
  1033. require: ['datepicker', '?^ngModel'],
  1034. controller: 'DatepickerController',
  1035. link: function(scope, element, attrs, ctrls) {
  1036. var datepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];
  1037. if ( ngModelCtrl ) {
  1038. datepickerCtrl.init( ngModelCtrl );
  1039. }
  1040. }
  1041. };
  1042. })
  1043. .directive('daypicker', ['dateFilter', function (dateFilter) {
  1044. return {
  1045. restrict: 'EA',
  1046. replace: true,
  1047. templateUrl: 'template/datepicker/day.html',
  1048. require: '^datepicker',
  1049. link: function(scope, element, attrs, ctrl) {
  1050. scope.showWeeks = ctrl.showWeeks;
  1051. ctrl.step = { months: 1 };
  1052. ctrl.element = element;
  1053. var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  1054. function getDaysInMonth( year, month ) {
  1055. return ((month === 1) && (year % 4 === 0) && ((year % 100 !== 0) || (year % 400 === 0))) ? 29 : DAYS_IN_MONTH[month];
  1056. }
  1057. function getDates(startDate, n) {
  1058. var dates = new Array(n), current = new Date(startDate), i = 0;
  1059. current.setHours(12); // Prevent repeated dates because of timezone bug
  1060. while ( i < n ) {
  1061. dates[i++] = new Date(current);
  1062. current.setDate( current.getDate() + 1 );
  1063. }
  1064. return dates;
  1065. }
  1066. ctrl._refreshView = function() {
  1067. var year = ctrl.activeDate.getFullYear(),
  1068. month = ctrl.activeDate.getMonth(),
  1069. firstDayOfMonth = new Date(year, month, 1),
  1070. difference = ctrl.startingDay - firstDayOfMonth.getDay(),
  1071. numDisplayedFromPreviousMonth = (difference > 0) ? 7 - difference : - difference,
  1072. firstDate = new Date(firstDayOfMonth);
  1073. if ( numDisplayedFromPreviousMonth > 0 ) {
  1074. firstDate.setDate( - numDisplayedFromPreviousMonth + 1 );
  1075. }
  1076. // 42 is the number of days on a six-month calendar
  1077. var days = getDates(firstDate, 42);
  1078. for (var i = 0; i < 42; i ++) {
  1079. days[i] = angular.extend(ctrl.createDateObject(days[i], ctrl.formatDay), {
  1080. secondary: days[i].getMonth() !== month,
  1081. uid: scope.uniqueId + '-' + i
  1082. });
  1083. }
  1084. scope.labels = new Array(7);
  1085. for (var j = 0; j < 7; j++) {
  1086. scope.labels[j] = {
  1087. abbr: dateFilter(days[j].date, ctrl.formatDayHeader),
  1088. full: dateFilter(days[j].date, 'EEEE')
  1089. };
  1090. }
  1091. scope.title = dateFilter(ctrl.activeDate, ctrl.formatDayTitle);
  1092. scope.rows = ctrl.split(days, 7);
  1093. if ( scope.showWeeks ) {
  1094. scope.weekNumbers = [];
  1095. var weekNumber = getISO8601WeekNumber( scope.rows[0][0].date ),
  1096. numWeeks = scope.rows.length;
  1097. while( scope.weekNumbers.push(weekNumber++) < numWeeks ) {}
  1098. }
  1099. };
  1100. ctrl.compare = function(date1, date2) {
  1101. return (new Date( date1.getFullYear(), date1.getMonth(), date1.getDate() ) - new Date( date2.getFullYear(), date2.getMonth(), date2.getDate() ) );
  1102. };
  1103. function getISO8601WeekNumber(date) {
  1104. var checkDate = new Date(date);
  1105. checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); // Thursday
  1106. var time = checkDate.getTime();
  1107. checkDate.setMonth(0); // Compare with Jan 1
  1108. checkDate.setDate(1);
  1109. return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
  1110. }
  1111. ctrl.handleKeyDown = function( key, evt ) {
  1112. var date = ctrl.activeDate.getDate();
  1113. if (key === 'left') {
  1114. date = date - 1; // up
  1115. } else if (key === 'up') {
  1116. date = date - 7; // down
  1117. } else if (key === 'right') {
  1118. date = date + 1; // down
  1119. } else if (key === 'down') {
  1120. date = date + 7;
  1121. } else if (key === 'pageup' || key === 'pagedown') {
  1122. var month = ctrl.activeDate.getMonth() + (key === 'pageup' ? - 1 : 1);
  1123. ctrl.activeDate.setMonth(month, 1);
  1124. date = Math.min(getDaysInMonth(ctrl.activeDate.getFullYear(), ctrl.activeDate.getMonth()), date);
  1125. } else if (key === 'home') {
  1126. date = 1;
  1127. } else if (key === 'end') {
  1128. date = getDaysInMonth(ctrl.activeDate.getFullYear(), ctrl.activeDate.getMonth());
  1129. }
  1130. ctrl.activeDate.setDate(date);
  1131. };
  1132. ctrl.refreshView();
  1133. }
  1134. };
  1135. }])
  1136. .directive('monthpicker', ['dateFilter', function (dateFilter) {
  1137. return {
  1138. restrict: 'EA',
  1139. replace: true,
  1140. templateUrl: 'template/datepicker/month.html',
  1141. require: '^datepicker',
  1142. link: function(scope, element, attrs, ctrl) {
  1143. ctrl.step = { years: 1 };
  1144. ctrl.element = element;
  1145. ctrl._refreshView = function() {
  1146. var months = new Array(12),
  1147. year = ctrl.activeDate.getFullYear();
  1148. for ( var i = 0; i < 12; i++ ) {
  1149. months[i] = angular.extend(ctrl.createDateObject(new Date(year, i, 1), ctrl.formatMonth), {
  1150. uid: scope.uniqueId + '-' + i
  1151. });
  1152. }
  1153. scope.title = dateFilter(ctrl.activeDate, ctrl.formatMonthTitle);
  1154. scope.rows = ctrl.split(months, 3);
  1155. };
  1156. ctrl.compare = function(date1, date2) {
  1157. return new Date( date1.getFullYear(), date1.getMonth() ) - new Date( date2.getFullYear(), date2.getMonth() );
  1158. };
  1159. ctrl.handleKeyDown = function( key, evt ) {
  1160. var date = ctrl.activeDate.getMonth();
  1161. if (key === 'left') {
  1162. date = date - 1; // up
  1163. } else if (key === 'up') {
  1164. date = date - 3; // down
  1165. } else if (key === 'right') {
  1166. date = date + 1; // down
  1167. } else if (key === 'down') {
  1168. date = date + 3;
  1169. } else if (key === 'pageup' || key === 'pagedown') {
  1170. var year = ctrl.activeDate.getFullYear() + (key === 'pageup' ? - 1 : 1);
  1171. ctrl.activeDate.setFullYear(year);
  1172. } else if (key === 'home') {
  1173. date = 0;
  1174. } else if (key === 'end') {
  1175. date = 11;
  1176. }
  1177. ctrl.activeDate.setMonth(date);
  1178. };
  1179. ctrl.refreshView();
  1180. }
  1181. };
  1182. }])
  1183. .directive('yearpicker', ['dateFilter', function (dateFilter) {
  1184. return {
  1185. restrict: 'EA',
  1186. replace: true,
  1187. templateUrl: 'template/datepicker/year.html',
  1188. require: '^datepicker',
  1189. link: function(scope, element, attrs, ctrl) {
  1190. var range = ctrl.yearRange;
  1191. ctrl.step = { years: range };
  1192. ctrl.element = element;
  1193. function getStartingYear( year ) {
  1194. return parseInt((year - 1) / range, 10) * range + 1;
  1195. }
  1196. ctrl._refreshView = function() {
  1197. var years = new Array(range);
  1198. for ( var i = 0, start = getStartingYear(ctrl.activeDate.getFullYear()); i < range; i++ ) {
  1199. years[i] = angular.extend(ctrl.createDateObject(new Date(start + i, 0, 1), ctrl.formatYear), {
  1200. uid: scope.uniqueId + '-' + i
  1201. });
  1202. }
  1203. scope.title = [years[0].label, years[range - 1].label].join(' - ');
  1204. scope.rows = ctrl.split(years, 5);
  1205. };
  1206. ctrl.compare = function(date1, date2) {
  1207. return date1.getFullYear() - date2.getFullYear();
  1208. };
  1209. ctrl.handleKeyDown = function( key, evt ) {
  1210. var date = ctrl.activeDate.getFullYear();
  1211. if (key === 'left') {
  1212. date = date - 1; // up
  1213. } else if (key === 'up') {
  1214. date = date - 5; // down
  1215. } else if (key === 'right') {
  1216. date = date + 1; // down
  1217. } else if (key === 'down') {
  1218. date = date + 5;
  1219. } else if (key === 'pageup' || key === 'pagedown') {
  1220. date += (key === 'pageup' ? - 1 : 1) * ctrl.step.years;
  1221. } else if (key === 'home') {
  1222. date = getStartingYear( ctrl.activeDate.getFullYear() );
  1223. } else if (key === 'end') {
  1224. date = getStartingYear( ctrl.activeDate.getFullYear() ) + range - 1;
  1225. }
  1226. ctrl.activeDate.setFullYear(date);
  1227. };
  1228. ctrl.refreshView();
  1229. }
  1230. };
  1231. }])
  1232. .constant('datepickerPopupConfig', {
  1233. datepickerPopup: 'yyyy-MM-dd',
  1234. currentText: 'Today',
  1235. clearText: 'Clear',
  1236. closeText: 'Done',
  1237. closeOnDateSelection: true,
  1238. appendToBody: false,
  1239. showButtonBar: true
  1240. })
  1241. .directive('datepickerPopup', ['$compile', '$parse', '$document', '$position', 'dateFilter', 'dateParser', 'datepickerPopupConfig',
  1242. function ($compile, $parse, $document, $position, dateFilter, dateParser, datepickerPopupConfig) {
  1243. return {
  1244. restrict: 'EA',
  1245. require: 'ngModel',
  1246. scope: {
  1247. isOpen: '=?',
  1248. currentText: '@',
  1249. clearText: '@',
  1250. closeText: '@',
  1251. dateDisabled: '&'
  1252. },
  1253. link: function(scope, element, attrs, ngModel) {
  1254. var dateFormat,
  1255. closeOnDateSelection = angular.isDefined(attrs.closeOnDateSelection) ? scope.$parent.$eval(attrs.closeOnDateSelection) : datepickerPopupConfig.closeOnDateSelection,
  1256. appendToBody = angular.isDefined(attrs.datepickerAppendToBody) ? scope.$parent.$eval(attrs.datepickerAppendToBody) : datepickerPopupConfig.appendToBody;
  1257. scope.showButtonBar = angular.isDefined(attrs.showButtonBar) ? scope.$parent.$eval(attrs.showButtonBar) : datepickerPopupConfig.showButtonBar;
  1258. scope.getText = function( key ) {
  1259. return scope[key + 'Text'] || datepickerPopupConfig[key + 'Text'];
  1260. };
  1261. attrs.$observe('datepickerPopup', function(value) {
  1262. dateFormat = value || datepickerPopupConfig.datepickerPopup;
  1263. ngModel.$render();
  1264. });
  1265. // popup element used to display calendar
  1266. var popupEl = angular.element('<div datepicker-popup-wrap><div datepicker></div></div>');
  1267. popupEl.attr({
  1268. 'ng-model': 'date',
  1269. 'ng-change': 'dateSelection()'
  1270. });
  1271. function cameltoDash( string ){
  1272. return string.replace(/([A-Z])/g, function($1) { return '-' + $1.toLowerCase(); });
  1273. }
  1274. // datepicker element
  1275. var datepickerEl = angular.element(popupEl.children()[0]);
  1276. if ( attrs.datepickerOptions ) {
  1277. angular.forEach(scope.$parent.$eval(attrs.datepickerOptions), function( value, option ) {
  1278. datepickerEl.attr( cameltoDash(option), value );
  1279. });
  1280. }
  1281. scope.watchData = {};
  1282. angular.forEach(['minDate', 'maxDate', 'datepickerMode'], function( key ) {
  1283. if ( attrs[key] ) {
  1284. var getAttribute = $parse(attrs[key]);
  1285. scope.$parent.$watch(getAttribute, function(value){
  1286. scope.watchData[key] = value;
  1287. });
  1288. datepickerEl.attr(cameltoDash(key), 'watchData.' + key);
  1289. // Propagate changes from datepicker to outside
  1290. if ( key === 'datepickerMode' ) {
  1291. var setAttribute = getAttribute.assign;
  1292. scope.$watch('watchData.' + key, function(value, oldvalue) {
  1293. if ( value !== oldvalue ) {
  1294. setAttribute(scope.$parent, value);
  1295. }
  1296. });
  1297. }
  1298. }
  1299. });
  1300. if (attrs.dateDisabled) {
  1301. datepickerEl.attr('date-disabled', 'dateDisabled({ date: date, mode: mode })');
  1302. }
  1303. function parseDate(viewValue) {
  1304. if (!viewValue) {
  1305. ngModel.$setValidity('date', true);
  1306. return null;
  1307. } else if (angular.isDate(viewValue) && !isNaN(viewValue)) {
  1308. ngModel.$setValidity('date', true);
  1309. return viewValue;
  1310. } else if (angular.isString(viewValue)) {
  1311. var date = dateParser.parse(viewValue, dateFormat) || new Date(viewValue);
  1312. if (isNaN(date)) {
  1313. ngModel.$setValidity('date', false);
  1314. return undefined;
  1315. } else {
  1316. ngModel.$setValidity('date', true);
  1317. return date;
  1318. }
  1319. } else {
  1320. ngModel.$setValidity('date', false);
  1321. return undefined;
  1322. }
  1323. }
  1324. ngModel.$parsers.unshift(parseDate);
  1325. ngModel.$formatters.push(function (value) {
  1326. return ngModel.$isEmpty(value) ? value : dateFilter(value, dateFormat);
  1327. });
  1328. // Inner change
  1329. scope.dateSelection = function(dt) {
  1330. if (angular.isDefined(dt)) {
  1331. scope.date = dt;
  1332. }
  1333. ngModel.$setViewValue(scope.date);
  1334. ngModel.$render();
  1335. if ( closeOnDateSelection ) {
  1336. scope.isOpen = false;
  1337. element[0].focus();
  1338. }
  1339. };
  1340. element.bind('input change keyup', function() {
  1341. scope.$apply(function() {
  1342. scope.date = ngModel.$modelValue;
  1343. });
  1344. });
  1345. // Outer change
  1346. ngModel.$render = function() {
  1347. var date = ngModel.$viewValue ? dateFilter(parseDate(ngModel.$viewValue), dateFormat) : '';
  1348. element.val(date);
  1349. scope.date = parseDate( ngModel.$modelValue );
  1350. };
  1351. var documentClickBind = function(event) {
  1352. if (scope.isOpen && event.target !== element[0]) {
  1353. scope.$apply(function() {
  1354. scope.isOpen = false;
  1355. });
  1356. }
  1357. };
  1358. var keydown = function(evt, noApply) {
  1359. scope.keydown(evt);
  1360. };
  1361. element.bind('keydown', keydown);
  1362. scope.keydown = function(evt) {
  1363. if (evt.which === 27) {
  1364. evt.preventDefault();
  1365. evt.stopPropagation();
  1366. scope.close();
  1367. } else if (evt.which === 40 && !scope.isOpen) {
  1368. scope.isOpen = true;
  1369. }
  1370. };
  1371. scope.$watch('isOpen', function(value) {
  1372. if (value) {
  1373. scope.$broadcast('datepicker.focus');
  1374. scope.position = appendToBody ? $position.offset(element) : $position.position(element);
  1375. scope.position.top = scope.position.top + element.prop('offsetHeight');
  1376. $document.bind('click', documentClickBind);
  1377. } else {
  1378. $document.unbind('click', documentClickBind);
  1379. }
  1380. });
  1381. scope.select = function( date ) {
  1382. if (date === 'today') {
  1383. var today = new Date();
  1384. if (angular.isDate(ngModel.$modelValue)) {
  1385. date = new Date(ngModel.$modelValue);
  1386. date.setFullYear(today.getFullYear(), today.getMonth(), today.getDate());
  1387. } else {
  1388. date = new Date(today.setHours(0, 0, 0, 0));
  1389. }
  1390. }
  1391. scope.dateSelection( date );
  1392. };
  1393. scope.close = function() {
  1394. scope.isOpen = false;
  1395. element[0].focus();
  1396. };
  1397. var $popup = $compile(popupEl)(scope);
  1398. // Prevent jQuery cache memory leak (template is now redundant after linking)
  1399. popupEl.remove();
  1400. if ( appendToBody ) {
  1401. $document.find('body').append($popup);
  1402. } else {
  1403. element.after($popup);
  1404. }
  1405. scope.$on('$destroy', function() {
  1406. $popup.remove();
  1407. element.unbind('keydown', keydown);
  1408. $document.unbind('click', documentClickBind);
  1409. });
  1410. }
  1411. };
  1412. }])
  1413. .directive('datepickerPopupWrap', function() {
  1414. return {
  1415. restrict:'EA',
  1416. replace: true,
  1417. transclude: true,
  1418. templateUrl: 'template/datepicker/popup.html',
  1419. link:function (scope, element, attrs) {
  1420. element.bind('click', function(event) {
  1421. event.preventDefault();
  1422. event.stopPropagation();
  1423. });
  1424. }
  1425. };
  1426. });
  1427. angular.module('ui.bootstrap.dropdown', [])
  1428. .constant('dropdownConfig', {
  1429. openClass: 'open'
  1430. })
  1431. .service('dropdownService', ['$document', function($document) {
  1432. var openScope = null;
  1433. this.open = function( dropdownScope ) {
  1434. if ( !openScope ) {
  1435. $document.bind('click', closeDropdown);
  1436. $document.bind('keydown', escapeKeyBind);
  1437. }
  1438. if ( openScope && openScope !== dropdownScope ) {
  1439. openScope.isOpen = false;
  1440. }
  1441. openScope = dropdownScope;
  1442. };
  1443. this.close = function( dropdownScope ) {
  1444. if ( openScope === dropdownScope ) {
  1445. openScope = null;
  1446. $document.unbind('click', closeDropdown);
  1447. $document.unbind('keydown', escapeKeyBind);
  1448. }
  1449. };
  1450. var closeDropdown = function( evt ) {
  1451. // This method may still be called during the same mouse event that
  1452. // unbound this event handler. So check openScope before proceeding.
  1453. if (!openScope) { return; }
  1454. var toggleElement = openScope.getToggleElement();
  1455. if ( evt && toggleElement && toggleElement[0].contains(evt.target) ) {
  1456. return;
  1457. }
  1458. openScope.$apply(function() {
  1459. openScope.isOpen = false;
  1460. });
  1461. };
  1462. var escapeKeyBind = function( evt ) {
  1463. if ( evt.which === 27 ) {
  1464. openScope.focusToggleElement();
  1465. closeDropdown();
  1466. }
  1467. };
  1468. }])
  1469. .controller('DropdownController', ['$scope', '$attrs', '$parse', 'dropdownConfig', 'dropdownService', '$animate', function($scope, $attrs, $parse, dropdownConfig, dropdownService, $animate) {
  1470. var self = this,
  1471. scope = $scope.$new(), // create a child scope so we are not polluting original one
  1472. openClass = dropdownConfig.openClass,
  1473. getIsOpen,
  1474. setIsOpen = angular.noop,
  1475. toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop;
  1476. this.init = function( element ) {
  1477. self.$element = element;
  1478. if ( $attrs.isOpen ) {
  1479. getIsOpen = $parse($attrs.isOpen);
  1480. setIsOpen = getIsOpen.assign;
  1481. $scope.$watch(getIsOpen, function(value) {
  1482. scope.isOpen = !!value;
  1483. });
  1484. }
  1485. };
  1486. this.toggle = function( open ) {
  1487. return scope.isOpen = arguments.length ? !!open : !scope.isOpen;
  1488. };
  1489. // Allow other directives to watch status
  1490. this.isOpen = function() {
  1491. return scope.isOpen;
  1492. };
  1493. scope.getToggleElement = function() {
  1494. return self.toggleElement;
  1495. };
  1496. scope.focusToggleElement = function() {
  1497. if ( self.toggleElement ) {
  1498. self.toggleElement[0].focus();
  1499. }
  1500. };
  1501. scope.$watch('isOpen', function( isOpen, wasOpen ) {
  1502. $animate[isOpen ? 'addClass' : 'removeClass'](self.$element, openClass);
  1503. if ( isOpen ) {
  1504. scope.focusToggleElement();
  1505. dropdownService.open( scope );
  1506. } else {
  1507. dropdownService.close( scope );
  1508. }
  1509. setIsOpen($scope, isOpen);
  1510. if (angular.isDefined(isOpen) && isOpen !== wasOpen) {
  1511. toggleInvoker($scope, { open: !!isOpen });
  1512. }
  1513. });
  1514. $scope.$on('$locationChangeSuccess', function() {
  1515. scope.isOpen = false;
  1516. });
  1517. $scope.$on('$destroy', function() {
  1518. scope.$destroy();
  1519. });
  1520. }])
  1521. .directive('dropdown', function() {
  1522. return {
  1523. controller: 'DropdownController',
  1524. link: function(scope, element, attrs, dropdownCtrl) {
  1525. dropdownCtrl.init( element );
  1526. }
  1527. };
  1528. })
  1529. .directive('dropdownToggle', function() {
  1530. return {
  1531. require: '?^dropdown',
  1532. link: function(scope, element, attrs, dropdownCtrl) {
  1533. if ( !dropdownCtrl ) {
  1534. return;
  1535. }
  1536. dropdownCtrl.toggleElement = element;
  1537. var toggleDropdown = function(event) {
  1538. event.preventDefault();
  1539. if ( !element.hasClass('disabled') && !attrs.disabled ) {
  1540. scope.$apply(function() {
  1541. dropdownCtrl.toggle();
  1542. });
  1543. }
  1544. };
  1545. element.bind('click', toggleDropdown);
  1546. // WAI-ARIA
  1547. element.attr({ 'aria-haspopup': true, 'aria-expanded': false });
  1548. scope.$watch(dropdownCtrl.isOpen, function( isOpen ) {
  1549. element.attr('aria-expanded', !!isOpen);
  1550. });
  1551. scope.$on('$destroy', function() {
  1552. element.unbind('click', toggleDropdown);
  1553. });
  1554. }
  1555. };
  1556. });
  1557. angular.module('ui.bootstrap.modal', ['ui.bootstrap.transition'])
  1558. /**
  1559. * A helper, internal data structure that acts as a map but also allows getting / removing
  1560. * elements in the LIFO order
  1561. */
  1562. .factory('$$stackedMap', function () {
  1563. return {
  1564. createNew: function () {
  1565. var stack = [];
  1566. return {
  1567. add: function (key, value) {
  1568. stack.push({
  1569. key: key,
  1570. value: value
  1571. });
  1572. },
  1573. get: function (key) {
  1574. for (var i = 0; i < stack.length; i++) {
  1575. if (key == stack[i].key) {
  1576. return stack[i];
  1577. }
  1578. }
  1579. },
  1580. keys: function() {
  1581. var keys = [];
  1582. for (var i = 0; i < stack.length; i++) {
  1583. keys.push(stack[i].key);
  1584. }
  1585. return keys;
  1586. },
  1587. top: function () {
  1588. return stack[stack.length - 1];
  1589. },
  1590. remove: function (key) {
  1591. var idx = -1;
  1592. for (var i = 0; i < stack.length; i++) {
  1593. if (key == stack[i].key) {
  1594. idx = i;
  1595. break;
  1596. }
  1597. }
  1598. return stack.splice(idx, 1)[0];
  1599. },
  1600. removeTop: function () {
  1601. return stack.splice(stack.length - 1, 1)[0];
  1602. },
  1603. length: function () {
  1604. return stack.length;
  1605. }
  1606. };
  1607. }
  1608. };
  1609. })
  1610. /**
  1611. * A helper directive for the $modal service. It creates a backdrop element.
  1612. */
  1613. .directive('modalBackdrop', ['$timeout', function ($timeout) {
  1614. return {
  1615. restrict: 'EA',
  1616. replace: true,
  1617. templateUrl: 'template/modal/backdrop.html',
  1618. link: function (scope, element, attrs) {
  1619. scope.backdropClass = attrs.backdropClass || '';
  1620. scope.animate = false;
  1621. //trigger CSS transitions
  1622. $timeout(function () {
  1623. scope.animate = true;
  1624. });
  1625. }
  1626. };
  1627. }])
  1628. .directive('modalWindow', ['$modalStack', '$timeout', function ($modalStack, $timeout) {
  1629. return {
  1630. restrict: 'EA',
  1631. scope: {
  1632. index: '@',
  1633. animate: '='
  1634. },
  1635. replace: true,
  1636. transclude: true,
  1637. templateUrl: function(tElement, tAttrs) {
  1638. return tAttrs.templateUrl || 'template/modal/window.html';
  1639. },
  1640. link: function (scope, element, attrs) {
  1641. element.addClass(attrs.windowClass || '');
  1642. scope.size = attrs.size;
  1643. $timeout(function () {
  1644. // trigger CSS transitions
  1645. scope.animate = true;
  1646. /**
  1647. * Auto-focusing of a freshly-opened modal element causes any child elements
  1648. * with the autofocus attribute to lose focus. This is an issue on touch
  1649. * based devices which will show and then hide the onscreen keyboard.
  1650. * Attempts to refocus the autofocus element via JavaScript will not reopen
  1651. * the onscreen keyboard. Fixed by updated the focusing logic to only autofocus
  1652. * the modal element if the modal does not contain an autofocus element.
  1653. */
  1654. if (!element[0].querySelectorAll('[autofocus]').length) {
  1655. element[0].focus();
  1656. }
  1657. });
  1658. scope.close = function (evt) {
  1659. var modal = $modalStack.getTop();
  1660. if (modal && modal.value.backdrop && modal.value.backdrop != 'static' && (evt.target === evt.currentTarget)) {
  1661. evt.preventDefault();
  1662. evt.stopPropagation();
  1663. $modalStack.dismiss(modal.key, 'backdrop click');
  1664. }
  1665. };
  1666. }
  1667. };
  1668. }])
  1669. .directive('modalTransclude', function () {
  1670. return {
  1671. link: function($scope, $element, $attrs, controller, $transclude) {
  1672. $transclude($scope.$parent, function(clone) {
  1673. $element.empty();
  1674. $element.append(clone);
  1675. });
  1676. }
  1677. };
  1678. })
  1679. .factory('$modalStack', ['$transition', '$timeout', '$document', '$compile', '$rootScope', '$$stackedMap',
  1680. function ($transition, $timeout, $document, $compile, $rootScope, $$stackedMap) {
  1681. var OPENED_MODAL_CLASS = 'modal-open';
  1682. var backdropDomEl, backdropScope;
  1683. var openedWindows = $$stackedMap.createNew();
  1684. var $modalStack = {};
  1685. function backdropIndex() {
  1686. var topBackdropIndex = -1;
  1687. var opened = openedWindows.keys();
  1688. for (var i = 0; i < opened.length; i++) {
  1689. if (openedWindows.get(opened[i]).value.backdrop) {
  1690. topBackdropIndex = i;
  1691. }
  1692. }
  1693. return topBackdropIndex;
  1694. }
  1695. $rootScope.$watch(backdropIndex, function(newBackdropIndex){
  1696. if (backdropScope) {
  1697. backdropScope.index = newBackdropIndex;
  1698. }
  1699. });
  1700. function removeModalWindow(modalInstance) {
  1701. var body = $document.find('body').eq(0);
  1702. var modalWindow = openedWindows.get(modalInstance).value;
  1703. //clean up the stack
  1704. openedWindows.remove(modalInstance);
  1705. //remove window DOM element
  1706. removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, 300, function() {
  1707. modalWindow.modalScope.$destroy();
  1708. body.toggleClass(OPENED_MODAL_CLASS, openedWindows.length() > 0);
  1709. checkRemoveBackdrop();
  1710. });
  1711. }
  1712. function checkRemoveBackdrop() {
  1713. //remove backdrop if no longer needed
  1714. if (backdropDomEl && backdropIndex() == -1) {
  1715. var backdropScopeRef = backdropScope;
  1716. removeAfterAnimate(backdropDomEl, backdropScope, 150, function () {
  1717. backdropScopeRef.$destroy();
  1718. backdropScopeRef = null;
  1719. });
  1720. backdropDomEl = undefined;
  1721. backdropScope = undefined;
  1722. }
  1723. }
  1724. function removeAfterAnimate(domEl, scope, emulateTime, done) {
  1725. // Closing animation
  1726. scope.animate = false;
  1727. var transitionEndEventName = $transition.transitionEndEventName;
  1728. if (transitionEndEventName) {
  1729. // transition out
  1730. var timeout = $timeout(afterAnimating, emulateTime);
  1731. domEl.bind(transitionEndEventName, function () {
  1732. $timeout.cancel(timeout);
  1733. afterAnimating();
  1734. scope.$apply();
  1735. });
  1736. } else {
  1737. // Ensure this call is async
  1738. $timeout(afterAnimating);
  1739. }
  1740. function afterAnimating() {
  1741. if (afterAnimating.done) {
  1742. return;
  1743. }
  1744. afterAnimating.done = true;
  1745. domEl.remove();
  1746. if (done) {
  1747. done();
  1748. }
  1749. }
  1750. }
  1751. $document.bind('keydown', function (evt) {
  1752. var modal;
  1753. if (evt.which === 27) {
  1754. modal = openedWindows.top();
  1755. if (modal && modal.value.keyboard) {
  1756. evt.preventDefault();
  1757. $rootScope.$apply(function () {
  1758. $modalStack.dismiss(modal.key, 'escape key press');
  1759. });
  1760. }
  1761. }
  1762. });
  1763. $modalStack.open = function (modalInstance, modal) {
  1764. openedWindows.add(modalInstance, {
  1765. deferred: modal.deferred,
  1766. modalScope: modal.scope,
  1767. backdrop: modal.backdrop,
  1768. keyboard: modal.keyboard
  1769. });
  1770. var body = $document.find('body').eq(0),
  1771. currBackdropIndex = backdropIndex();
  1772. if (currBackdropIndex >= 0 && !backdropDomEl) {
  1773. backdropScope = $rootScope.$new(true);
  1774. backdropScope.index = currBackdropIndex;
  1775. var angularBackgroundDomEl = angular.element('<div modal-backdrop></div>');
  1776. angularBackgroundDomEl.attr('backdrop-class', modal.backdropClass);
  1777. backdropDomEl = $compile(angularBackgroundDomEl)(backdropScope);
  1778. body.append(backdropDomEl);
  1779. }
  1780. var angularDomEl = angular.element('<div modal-window></div>');
  1781. angularDomEl.attr({
  1782. 'template-url': modal.windowTemplateUrl,
  1783. 'window-class': modal.windowClass,
  1784. 'size': modal.size,
  1785. 'index': openedWindows.length() - 1,
  1786. 'animate': 'animate'
  1787. }).html(modal.content);
  1788. var modalDomEl = $compile(angularDomEl)(modal.scope);
  1789. openedWindows.top().value.modalDomEl = modalDomEl;
  1790. body.append(modalDomEl);
  1791. body.addClass(OPENED_MODAL_CLASS);
  1792. };
  1793. $modalStack.close = function (modalInstance, result) {
  1794. var modalWindow = openedWindows.get(modalInstance);
  1795. if (modalWindow) {
  1796. modalWindow.value.deferred.resolve(result);
  1797. removeModalWindow(modalInstance);
  1798. }
  1799. };
  1800. $modalStack.dismiss = function (modalInstance, reason) {
  1801. var modalWindow = openedWindows.get(modalInstance);
  1802. if (modalWindow) {
  1803. modalWindow.value.deferred.reject(reason);
  1804. removeModalWindow(modalInstance);
  1805. }
  1806. };
  1807. $modalStack.dismissAll = function (reason) {
  1808. var topModal = this.getTop();
  1809. while (topModal) {
  1810. this.dismiss(topModal.key, reason);
  1811. topModal = this.getTop();
  1812. }
  1813. };
  1814. $modalStack.getTop = function () {
  1815. return openedWindows.top();
  1816. };
  1817. return $modalStack;
  1818. }])
  1819. .provider('$modal', function () {
  1820. var $modalProvider = {
  1821. options: {
  1822. backdrop: true, //can be also false or 'static'
  1823. keyboard: true
  1824. },
  1825. $get: ['$injector', '$rootScope', '$q', '$http', '$templateCache', '$controller', '$modalStack',
  1826. function ($injector, $rootScope, $q, $http, $templateCache, $controller, $modalStack) {
  1827. var $modal = {};
  1828. function getTemplatePromise(options) {
  1829. return options.template ? $q.when(options.template) :
  1830. $http.get(angular.isFunction(options.templateUrl) ? (options.templateUrl)() : options.templateUrl,
  1831. {cache: $templateCache}).then(function (result) {
  1832. return result.data;
  1833. });
  1834. }
  1835. function getResolvePromises(resolves) {
  1836. var promisesArr = [];
  1837. angular.forEach(resolves, function (value) {
  1838. if (angular.isFunction(value) || angular.isArray(value)) {
  1839. promisesArr.push($q.when($injector.invoke(value)));
  1840. }
  1841. });
  1842. return promisesArr;
  1843. }
  1844. $modal.open = function (modalOptions) {
  1845. var modalResultDeferred = $q.defer();
  1846. var modalOpenedDeferred = $q.defer();
  1847. //prepare an instance of a modal to be injected into controllers and returned to a caller
  1848. var modalInstance = {
  1849. result: modalResultDeferred.promise,
  1850. opened: modalOpenedDeferred.promise,
  1851. close: function (result) {
  1852. $modalStack.close(modalInstance, result);
  1853. },
  1854. dismiss: function (reason) {
  1855. $modalStack.dismiss(modalInstance, reason);
  1856. }
  1857. };
  1858. //merge and clean up options
  1859. modalOptions = angular.extend({}, $modalProvider.options, modalOptions);
  1860. modalOptions.resolve = modalOptions.resolve || {};
  1861. //verify options
  1862. if (!modalOptions.template && !modalOptions.templateUrl) {
  1863. throw new Error('One of template or templateUrl options is required.');
  1864. }
  1865. var templateAndResolvePromise =
  1866. $q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve)));
  1867. templateAndResolvePromise.then(function resolveSuccess(tplAndVars) {
  1868. var modalScope = (modalOptions.scope || $rootScope).$new();
  1869. modalScope.$close = modalInstance.close;
  1870. modalScope.$dismiss = modalInstance.dismiss;
  1871. var ctrlInstance, ctrlLocals = {};
  1872. var resolveIter = 1;
  1873. //controllers
  1874. if (modalOptions.controller) {
  1875. ctrlLocals.$scope = modalScope;
  1876. ctrlLocals.$modalInstance = modalInstance;
  1877. angular.forEach(modalOptions.resolve, function (value, key) {
  1878. ctrlLocals[key] = tplAndVars[resolveIter++];
  1879. });
  1880. ctrlInstance = $controller(modalOptions.controller, ctrlLocals);
  1881. if (modalOptions.controllerAs) {
  1882. modalScope[modalOptions.controllerAs] = ctrlInstance;
  1883. }
  1884. }
  1885. $modalStack.open(modalInstance, {
  1886. scope: modalScope,
  1887. deferred: modalResultDeferred,
  1888. content: tplAndVars[0],
  1889. backdrop: modalOptions.backdrop,
  1890. keyboard: modalOptions.keyboard,
  1891. backdropClass: modalOptions.backdropClass,
  1892. windowClass: modalOptions.windowClass,
  1893. windowTemplateUrl: modalOptions.windowTemplateUrl,
  1894. size: modalOptions.size
  1895. });
  1896. }, function resolveError(reason) {
  1897. modalResultDeferred.reject(reason);
  1898. });
  1899. templateAndResolvePromise.then(function () {
  1900. modalOpenedDeferred.resolve(true);
  1901. }, function () {
  1902. modalOpenedDeferred.reject(false);
  1903. });
  1904. return modalInstance;
  1905. };
  1906. return $modal;
  1907. }]
  1908. };
  1909. return $modalProvider;
  1910. });
  1911. angular.module('ui.bootstrap.pagination', [])
  1912. .controller('PaginationController', ['$scope', '$attrs', '$parse', function ($scope, $attrs, $parse) {
  1913. var self = this,
  1914. ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl
  1915. setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop;
  1916. this.init = function(ngModelCtrl_, config) {
  1917. ngModelCtrl = ngModelCtrl_;
  1918. this.config = config;
  1919. ngModelCtrl.$render = function() {
  1920. self.render();
  1921. };
  1922. if ($attrs.itemsPerPage) {
  1923. $scope.$parent.$watch($parse($attrs.itemsPerPage), function(value) {
  1924. self.itemsPerPage = parseInt(value, 10);
  1925. $scope.totalPages = self.calculateTotalPages();
  1926. });
  1927. } else {
  1928. this.itemsPerPage = config.itemsPerPage;
  1929. }
  1930. };
  1931. this.calculateTotalPages = function() {
  1932. var totalPages = this.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / this.itemsPerPage);
  1933. return Math.max(totalPages || 0, 1);
  1934. };
  1935. this.render = function() {
  1936. $scope.page = parseInt(ngModelCtrl.$viewValue, 10) || 1;
  1937. };
  1938. $scope.selectPage = function(page) {
  1939. if ( $scope.page !== page && page > 0 && page <= $scope.totalPages) {
  1940. ngModelCtrl.$setViewValue(page);
  1941. ngModelCtrl.$render();
  1942. }
  1943. };
  1944. $scope.getText = function( key ) {
  1945. return $scope[key + 'Text'] || self.config[key + 'Text'];
  1946. };
  1947. $scope.noPrevious = function() {
  1948. return $scope.page === 1;
  1949. };
  1950. $scope.noNext = function() {
  1951. return $scope.page === $scope.totalPages;
  1952. };
  1953. $scope.$watch('totalItems', function() {
  1954. $scope.totalPages = self.calculateTotalPages();
  1955. });
  1956. $scope.$watch('totalPages', function(value) {
  1957. setNumPages($scope.$parent, value); // Readonly variable
  1958. if ( $scope.page > value ) {
  1959. $scope.selectPage(value);
  1960. } else {
  1961. ngModelCtrl.$render();
  1962. }
  1963. });
  1964. }])
  1965. .constant('paginationConfig', {
  1966. itemsPerPage: 10,
  1967. boundaryLinks: false,
  1968. directionLinks: true,
  1969. firstText: 'First',
  1970. previousText: 'Previous',
  1971. nextText: 'Next',
  1972. lastText: 'Last',
  1973. rotate: true
  1974. })
  1975. .directive('pagination', ['$parse', 'paginationConfig', function($parse, paginationConfig) {
  1976. return {
  1977. restrict: 'EA',
  1978. scope: {
  1979. totalItems: '=',
  1980. firstText: '@',
  1981. previousText: '@',
  1982. nextText: '@',
  1983. lastText: '@'
  1984. },
  1985. require: ['pagination', '?ngModel'],
  1986. controller: 'PaginationController',
  1987. templateUrl: 'template/pagination/pagination.html',
  1988. replace: true,
  1989. link: function(scope, element, attrs, ctrls) {
  1990. var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];
  1991. if (!ngModelCtrl) {
  1992. return; // do nothing if no ng-model
  1993. }
  1994. // Setup configuration parameters
  1995. var maxSize = angular.isDefined(attrs.maxSize) ? scope.$parent.$eval(attrs.maxSize) : paginationConfig.maxSize,
  1996. rotate = angular.isDefined(attrs.rotate) ? scope.$parent.$eval(attrs.rotate) : paginationConfig.rotate;
  1997. scope.boundaryLinks = angular.isDefined(attrs.boundaryLinks) ? scope.$parent.$eval(attrs.boundaryLinks) : paginationConfig.boundaryLinks;
  1998. scope.directionLinks = angular.isDefined(attrs.directionLinks) ? scope.$parent.$eval(attrs.directionLinks) : paginationConfig.directionLinks;
  1999. paginationCtrl.init(ngModelCtrl, paginationConfig);
  2000. if (attrs.maxSize) {
  2001. scope.$parent.$watch($parse(attrs.maxSize), function(value) {
  2002. maxSize = parseInt(value, 10);
  2003. paginationCtrl.render();
  2004. });
  2005. }
  2006. // Create page object used in template
  2007. function makePage(number, text, isActive) {
  2008. return {
  2009. number: number,
  2010. text: text,
  2011. active: isActive
  2012. };
  2013. }
  2014. function getPages(currentPage, totalPages) {
  2015. var pages = [];
  2016. // Default page limits
  2017. var startPage = 1, endPage = totalPages;
  2018. var isMaxSized = ( angular.isDefined(maxSize) && maxSize < totalPages );
  2019. // recompute if maxSize
  2020. if ( isMaxSized ) {
  2021. if ( rotate ) {
  2022. // Current page is displayed in the middle of the visible ones
  2023. startPage = Math.max(currentPage - Math.floor(maxSize/2), 1);
  2024. endPage = startPage + maxSize - 1;
  2025. // Adjust if limit is exceeded
  2026. if (endPage > totalPages) {
  2027. endPage = totalPages;
  2028. startPage = endPage - maxSize + 1;
  2029. }
  2030. } else {
  2031. // Visible pages are paginated with maxSize
  2032. startPage = ((Math.ceil(currentPage / maxSize) - 1) * maxSize) + 1;
  2033. // Adjust last page if limit is exceeded
  2034. endPage = Math.min(startPage + maxSize - 1, totalPages);
  2035. }
  2036. }
  2037. // Add page number links
  2038. for (var number = startPage; number <= endPage; number++) {
  2039. var page = makePage(number, number, number === currentPage);
  2040. pages.push(page);
  2041. }
  2042. // Add links to move between page sets
  2043. if ( isMaxSized && ! rotate ) {
  2044. if ( startPage > 1 ) {
  2045. var previousPageSet = makePage(startPage - 1, '...', false);
  2046. pages.unshift(previousPageSet);
  2047. }
  2048. if ( endPage < totalPages ) {
  2049. var nextPageSet = makePage(endPage + 1, '...', false);
  2050. pages.push(nextPageSet);
  2051. }
  2052. }
  2053. return pages;
  2054. }
  2055. var originalRender = paginationCtrl.render;
  2056. paginationCtrl.render = function() {
  2057. originalRender();
  2058. if (scope.page > 0 && scope.page <= scope.totalPages) {
  2059. scope.pages = getPages(scope.page, scope.totalPages);
  2060. }
  2061. };
  2062. }
  2063. };
  2064. }])
  2065. .constant('pagerConfig', {
  2066. itemsPerPage: 10,
  2067. previousText: '« Previous',
  2068. nextText: 'Next »',
  2069. align: true
  2070. })
  2071. .directive('pager', ['pagerConfig', function(pagerConfig) {
  2072. return {
  2073. restrict: 'EA',
  2074. scope: {
  2075. totalItems: '=',
  2076. previousText: '@',
  2077. nextText: '@'
  2078. },
  2079. require: ['pager', '?ngModel'],
  2080. controller: 'PaginationController',
  2081. templateUrl: 'template/pagination/pager.html',
  2082. replace: true,
  2083. link: function(scope, element, attrs, ctrls) {
  2084. var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];
  2085. if (!ngModelCtrl) {
  2086. return; // do nothing if no ng-model
  2087. }
  2088. scope.align = angular.isDefined(attrs.align) ? scope.$parent.$eval(attrs.align) : pagerConfig.align;
  2089. paginationCtrl.init(ngModelCtrl, pagerConfig);
  2090. }
  2091. };
  2092. }]);
  2093. /**
  2094. * The following features are still outstanding: animation as a
  2095. * function, placement as a function, inside, support for more triggers than
  2096. * just mouse enter/leave, html tooltips, and selector delegation.
  2097. */
  2098. angular.module( 'ui.bootstrap.tooltip', [ 'ui.bootstrap.position', 'ui.bootstrap.bindHtml' ] )
  2099. /**
  2100. * The $tooltip service creates tooltip- and popover-like directives as well as
  2101. * houses global options for them.
  2102. */
  2103. .provider( '$tooltip', function () {
  2104. // The default options tooltip and popover.
  2105. var defaultOptions = {
  2106. placement: 'top',
  2107. animation: true,
  2108. popupDelay: 0
  2109. };
  2110. // Default hide triggers for each show trigger
  2111. var triggerMap = {
  2112. 'mouseenter': 'mouseleave',
  2113. 'click': 'click',
  2114. 'focus': 'blur'
  2115. };
  2116. // The options specified to the provider globally.
  2117. var globalOptions = {};
  2118. /**
  2119. * `options({})` allows global configuration of all tooltips in the
  2120. * application.
  2121. *
  2122. * var app = angular.module( 'App', ['ui.bootstrap.tooltip'], function( $tooltipProvider ) {
  2123. * // place tooltips left instead of top by default
  2124. * $tooltipProvider.options( { placement: 'left' } );
  2125. * });
  2126. */
  2127. this.options = function( value ) {
  2128. angular.extend( globalOptions, value );
  2129. };
  2130. /**
  2131. * This allows you to extend the set of trigger mappings available. E.g.:
  2132. *
  2133. * $tooltipProvider.setTriggers( 'openTrigger': 'closeTrigger' );
  2134. */
  2135. this.setTriggers = function setTriggers ( triggers ) {
  2136. angular.extend( triggerMap, triggers );
  2137. };
  2138. /**
  2139. * This is a helper function for translating camel-case to snake-case.
  2140. */
  2141. function snake_case(name){
  2142. var regexp = /[A-Z]/g;
  2143. var separator = '-';
  2144. return name.replace(regexp, function(letter, pos) {
  2145. return (pos ? separator : '') + letter.toLowerCase();
  2146. });
  2147. }
  2148. /**
  2149. * Returns the actual instance of the $tooltip service.
  2150. * TODO support multiple triggers
  2151. */
  2152. this.$get = [ '$window', '$compile', '$timeout', '$document', '$position', '$interpolate', function ( $window, $compile, $timeout, $document, $position, $interpolate ) {
  2153. return function $tooltip ( type, prefix, defaultTriggerShow ) {
  2154. var options = angular.extend( {}, defaultOptions, globalOptions );
  2155. /**
  2156. * Returns an object of show and hide triggers.
  2157. *
  2158. * If a trigger is supplied,
  2159. * it is used to show the tooltip; otherwise, it will use the `trigger`
  2160. * option passed to the `$tooltipProvider.options` method; else it will
  2161. * default to the trigger supplied to this directive factory.
  2162. *
  2163. * The hide trigger is based on the show trigger. If the `trigger` option
  2164. * was passed to the `$tooltipProvider.options` method, it will use the
  2165. * mapped trigger from `triggerMap` or the passed trigger if the map is
  2166. * undefined; otherwise, it uses the `triggerMap` value of the show
  2167. * trigger; else it will just use the show trigger.
  2168. */
  2169. function getTriggers ( trigger ) {
  2170. var show = trigger || options.trigger || defaultTriggerShow;
  2171. var hide = triggerMap[show] || show;
  2172. return {
  2173. show: show,
  2174. hide: hide
  2175. };
  2176. }
  2177. var directiveName = snake_case( type );
  2178. var startSym = $interpolate.startSymbol();
  2179. var endSym = $interpolate.endSymbol();
  2180. var template =
  2181. '<div '+ directiveName +'-popup '+
  2182. 'title="'+startSym+'title'+endSym+'" '+
  2183. 'content="'+startSym+'content'+endSym+'" '+
  2184. 'placement="'+startSym+'placement'+endSym+'" '+
  2185. 'animation="animation" '+
  2186. 'is-open="isOpen"'+
  2187. '>'+
  2188. '</div>';
  2189. return {
  2190. restrict: 'EA',
  2191. compile: function (tElem, tAttrs) {
  2192. var tooltipLinker = $compile( template );
  2193. return function link ( scope, element, attrs ) {
  2194. var tooltip;
  2195. var tooltipLinkedScope;
  2196. var transitionTimeout;
  2197. var popupTimeout;
  2198. var appendToBody = angular.isDefined( options.appendToBody ) ? options.appendToBody : false;
  2199. var triggers = getTriggers( undefined );
  2200. var hasEnableExp = angular.isDefined(attrs[prefix+'Enable']);
  2201. var ttScope = scope.$new(true);
  2202. var positionTooltip = function () {
  2203. var ttPosition = $position.positionElements(element, tooltip, ttScope.placement, appendToBody);
  2204. ttPosition.top += 'px';
  2205. ttPosition.left += 'px';
  2206. // Now set the calculated positioning.
  2207. tooltip.css( ttPosition );
  2208. };
  2209. // By default, the tooltip is not open.
  2210. // TODO add ability to start tooltip opened
  2211. ttScope.isOpen = false;
  2212. function toggleTooltipBind () {
  2213. if ( ! ttScope.isOpen ) {
  2214. showTooltipBind();
  2215. } else {
  2216. hideTooltipBind();
  2217. }
  2218. }
  2219. // Show the tooltip with delay if specified, otherwise show it immediately
  2220. function showTooltipBind() {
  2221. if(hasEnableExp && !scope.$eval(attrs[prefix+'Enable'])) {
  2222. return;
  2223. }
  2224. prepareTooltip();
  2225. if ( ttScope.popupDelay ) {
  2226. // Do nothing if the tooltip was already scheduled to pop-up.
  2227. // This happens if show is triggered multiple times before any hide is triggered.
  2228. if (!popupTimeout) {
  2229. popupTimeout = $timeout( show, ttScope.popupDelay, false );
  2230. popupTimeout.then(function(reposition){reposition();});
  2231. }
  2232. } else {
  2233. show()();
  2234. }
  2235. }
  2236. function hideTooltipBind () {
  2237. scope.$apply(function () {
  2238. hide();
  2239. });
  2240. }
  2241. // Show the tooltip popup element.
  2242. function show() {
  2243. popupTimeout = null;
  2244. // If there is a pending remove transition, we must cancel it, lest the
  2245. // tooltip be mysteriously removed.
  2246. if ( transitionTimeout ) {
  2247. $timeout.cancel( transitionTimeout );
  2248. transitionTimeout = null;
  2249. }
  2250. // Don't show empty tooltips.
  2251. if ( ! ttScope.content ) {
  2252. return angular.noop;
  2253. }
  2254. createTooltip();
  2255. // Set the initial positioning.
  2256. tooltip.css({ top: 0, left: 0, display: 'block' });
  2257. ttScope.$digest();
  2258. positionTooltip();
  2259. // And show the tooltip.
  2260. ttScope.isOpen = true;
  2261. ttScope.$digest(); // digest required as $apply is not called
  2262. // Return positioning function as promise callback for correct
  2263. // positioning after draw.
  2264. return positionTooltip;
  2265. }
  2266. // Hide the tooltip popup element.
  2267. function hide() {
  2268. // First things first: we don't show it anymore.
  2269. ttScope.isOpen = false;
  2270. //if tooltip is going to be shown after delay, we must cancel this
  2271. $timeout.cancel( popupTimeout );
  2272. popupTimeout = null;
  2273. // And now we remove it from the DOM. However, if we have animation, we
  2274. // need to wait for it to expire beforehand.
  2275. // FIXME: this is a placeholder for a port of the transitions library.
  2276. if ( ttScope.animation ) {
  2277. if (!transitionTimeout) {
  2278. transitionTimeout = $timeout(removeTooltip, 500);
  2279. }
  2280. } else {
  2281. removeTooltip();
  2282. }
  2283. }
  2284. function createTooltip() {
  2285. // There can only be one tooltip element per directive shown at once.
  2286. if (tooltip) {
  2287. removeTooltip();
  2288. }
  2289. tooltipLinkedScope = ttScope.$new();
  2290. tooltip = tooltipLinker(tooltipLinkedScope, function (tooltip) {
  2291. if ( appendToBody ) {
  2292. $document.find( 'body' ).append( tooltip );
  2293. } else {
  2294. element.after( tooltip );
  2295. }
  2296. });
  2297. }
  2298. function removeTooltip() {
  2299. transitionTimeout = null;
  2300. if (tooltip) {
  2301. tooltip.remove();
  2302. tooltip = null;
  2303. }
  2304. if (tooltipLinkedScope) {
  2305. tooltipLinkedScope.$destroy();
  2306. tooltipLinkedScope = null;
  2307. }
  2308. }
  2309. function prepareTooltip() {
  2310. prepPlacement();
  2311. prepPopupDelay();
  2312. }
  2313. /**
  2314. * Observe the relevant attributes.
  2315. */
  2316. attrs.$observe( type, function ( val ) {
  2317. ttScope.content = val;
  2318. if (!val && ttScope.isOpen ) {
  2319. hide();
  2320. }
  2321. });
  2322. attrs.$observe( prefix+'Title', function ( val ) {
  2323. ttScope.title = val;
  2324. });
  2325. function prepPlacement() {
  2326. var val = attrs[ prefix + 'Placement' ];
  2327. ttScope.placement = angular.isDefined( val ) ? val : options.placement;
  2328. }
  2329. function prepPopupDelay() {
  2330. var val = attrs[ prefix + 'PopupDelay' ];
  2331. var delay = parseInt( val, 10 );
  2332. ttScope.popupDelay = ! isNaN(delay) ? delay : options.popupDelay;
  2333. }
  2334. var unregisterTriggers = function () {
  2335. element.unbind(triggers.show, showTooltipBind);
  2336. element.unbind(triggers.hide, hideTooltipBind);
  2337. };
  2338. function prepTriggers() {
  2339. var val = attrs[ prefix + 'Trigger' ];
  2340. unregisterTriggers();
  2341. triggers = getTriggers( val );
  2342. if ( triggers.show === triggers.hide ) {
  2343. element.bind( triggers.show, toggleTooltipBind );
  2344. } else {
  2345. element.bind( triggers.show, showTooltipBind );
  2346. element.bind( triggers.hide, hideTooltipBind );
  2347. }
  2348. }
  2349. prepTriggers();
  2350. var animation = scope.$eval(attrs[prefix + 'Animation']);
  2351. ttScope.animation = angular.isDefined(animation) ? !!animation : options.animation;
  2352. var appendToBodyVal = scope.$eval(attrs[prefix + 'AppendToBody']);
  2353. appendToBody = angular.isDefined(appendToBodyVal) ? appendToBodyVal : appendToBody;
  2354. // if a tooltip is attached to <body> we need to remove it on
  2355. // location change as its parent scope will probably not be destroyed
  2356. // by the change.
  2357. if ( appendToBody ) {
  2358. scope.$on('$locationChangeSuccess', function closeTooltipOnLocationChangeSuccess () {
  2359. if ( ttScope.isOpen ) {
  2360. hide();
  2361. }
  2362. });
  2363. }
  2364. // Make sure tooltip is destroyed and removed.
  2365. scope.$on('$destroy', function onDestroyTooltip() {
  2366. $timeout.cancel( transitionTimeout );
  2367. $timeout.cancel( popupTimeout );
  2368. unregisterTriggers();
  2369. removeTooltip();
  2370. ttScope = null;
  2371. });
  2372. };
  2373. }
  2374. };
  2375. };
  2376. }];
  2377. })
  2378. .directive( 'tooltipPopup', function () {
  2379. return {
  2380. restrict: 'EA',
  2381. replace: true,
  2382. scope: { content: '@', placement: '@', animation: '&', isOpen: '&' },
  2383. templateUrl: 'template/tooltip/tooltip-popup.html'
  2384. };
  2385. })
  2386. .directive( 'tooltip', [ '$tooltip', function ( $tooltip ) {
  2387. return $tooltip( 'tooltip', 'tooltip', 'mouseenter' );
  2388. }])
  2389. .directive( 'tooltipHtmlUnsafePopup', function () {
  2390. return {
  2391. restrict: 'EA',
  2392. replace: true,
  2393. scope: { content: '@', placement: '@', animation: '&', isOpen: '&' },
  2394. templateUrl: 'template/tooltip/tooltip-html-unsafe-popup.html'
  2395. };
  2396. })
  2397. .directive( 'tooltipHtmlUnsafe', [ '$tooltip', function ( $tooltip ) {
  2398. return $tooltip( 'tooltipHtmlUnsafe', 'tooltip', 'mouseenter' );
  2399. }]);
  2400. /**
  2401. * The following features are still outstanding: popup delay, animation as a
  2402. * function, placement as a function, inside, support for more triggers than
  2403. * just mouse enter/leave, html popovers, and selector delegatation.
  2404. */
  2405. angular.module( 'ui.bootstrap.popover', [ 'ui.bootstrap.tooltip' ] )
  2406. .directive( 'popoverPopup', function () {
  2407. return {
  2408. restrict: 'EA',
  2409. replace: true,
  2410. scope: { title: '@', content: '@', placement: '@', animation: '&', isOpen: '&' },
  2411. templateUrl: 'template/popover/popover.html'
  2412. };
  2413. })
  2414. .directive( 'popover', [ '$tooltip', function ( $tooltip ) {
  2415. return $tooltip( 'popover', 'popover', 'click' );
  2416. }]);
  2417. angular.module('ui.bootstrap.progressbar', [])
  2418. .constant('progressConfig', {
  2419. animate: true,
  2420. max: 100
  2421. })
  2422. .controller('ProgressController', ['$scope', '$attrs', 'progressConfig', function($scope, $attrs, progressConfig) {
  2423. var self = this,
  2424. animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate;
  2425. this.bars = [];
  2426. $scope.max = angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : progressConfig.max;
  2427. this.addBar = function(bar, element) {
  2428. if ( !animate ) {
  2429. element.css({'transition': 'none'});
  2430. }
  2431. this.bars.push(bar);
  2432. bar.$watch('value', function( value ) {
  2433. bar.percent = +(100 * value / $scope.max).toFixed(2);
  2434. });
  2435. bar.$on('$destroy', function() {
  2436. element = null;
  2437. self.removeBar(bar);
  2438. });
  2439. };
  2440. this.removeBar = function(bar) {
  2441. this.bars.splice(this.bars.indexOf(bar), 1);
  2442. };
  2443. }])
  2444. .directive('progress', function() {
  2445. return {
  2446. restrict: 'EA',
  2447. replace: true,
  2448. transclude: true,
  2449. controller: 'ProgressController',
  2450. require: 'progress',
  2451. scope: {},
  2452. templateUrl: 'template/progressbar/progress.html'
  2453. };
  2454. })
  2455. .directive('bar', function() {
  2456. return {
  2457. restrict: 'EA',
  2458. replace: true,
  2459. transclude: true,
  2460. require: '^progress',
  2461. scope: {
  2462. value: '=',
  2463. type: '@'
  2464. },
  2465. templateUrl: 'template/progressbar/bar.html',
  2466. link: function(scope, element, attrs, progressCtrl) {
  2467. progressCtrl.addBar(scope, element);
  2468. }
  2469. };
  2470. })
  2471. .directive('progressbar', function() {
  2472. return {
  2473. restrict: 'EA',
  2474. replace: true,
  2475. transclude: true,
  2476. controller: 'ProgressController',
  2477. scope: {
  2478. value: '=',
  2479. type: '@'
  2480. },
  2481. templateUrl: 'template/progressbar/progressbar.html',
  2482. link: function(scope, element, attrs, progressCtrl) {
  2483. progressCtrl.addBar(scope, angular.element(element.children()[0]));
  2484. }
  2485. };
  2486. });
  2487. angular.module('ui.bootstrap.rating', [])
  2488. .constant('ratingConfig', {
  2489. max: 5,
  2490. stateOn: null,
  2491. stateOff: null
  2492. })
  2493. .controller('RatingController', ['$scope', '$attrs', 'ratingConfig', function($scope, $attrs, ratingConfig) {
  2494. var ngModelCtrl = { $setViewValue: angular.noop };
  2495. this.init = function(ngModelCtrl_) {
  2496. ngModelCtrl = ngModelCtrl_;
  2497. ngModelCtrl.$render = this.render;
  2498. this.stateOn = angular.isDefined($attrs.stateOn) ? $scope.$parent.$eval($attrs.stateOn) : ratingConfig.stateOn;
  2499. this.stateOff = angular.isDefined($attrs.stateOff) ? $scope.$parent.$eval($attrs.stateOff) : ratingConfig.stateOff;
  2500. var ratingStates = angular.isDefined($attrs.ratingStates) ? $scope.$parent.$eval($attrs.ratingStates) :
  2501. new Array( angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : ratingConfig.max );
  2502. $scope.range = this.buildTemplateObjects(ratingStates);
  2503. };
  2504. this.buildTemplateObjects = function(states) {
  2505. for (var i = 0, n = states.length; i < n; i++) {
  2506. states[i] = angular.extend({ index: i }, { stateOn: this.stateOn, stateOff: this.stateOff }, states[i]);
  2507. }
  2508. return states;
  2509. };
  2510. $scope.rate = function(value) {
  2511. if ( !$scope.readonly && value >= 0 && value <= $scope.range.length ) {
  2512. ngModelCtrl.$setViewValue(value);
  2513. ngModelCtrl.$render();
  2514. }
  2515. };
  2516. $scope.enter = function(value) {
  2517. if ( !$scope.readonly ) {
  2518. $scope.value = value;
  2519. }
  2520. $scope.onHover({value: value});
  2521. };
  2522. $scope.reset = function() {
  2523. $scope.value = ngModelCtrl.$viewValue;
  2524. $scope.onLeave();
  2525. };
  2526. $scope.onKeydown = function(evt) {
  2527. if (/(37|38|39|40)/.test(evt.which)) {
  2528. evt.preventDefault();
  2529. evt.stopPropagation();
  2530. $scope.rate( $scope.value + (evt.which === 38 || evt.which === 39 ? 1 : -1) );
  2531. }
  2532. };
  2533. this.render = function() {
  2534. $scope.value = ngModelCtrl.$viewValue;
  2535. };
  2536. }])
  2537. .directive('rating', function() {
  2538. return {
  2539. restrict: 'EA',
  2540. require: ['rating', 'ngModel'],
  2541. scope: {
  2542. readonly: '=?',
  2543. onHover: '&',
  2544. onLeave: '&'
  2545. },
  2546. controller: 'RatingController',
  2547. templateUrl: 'template/rating/rating.html',
  2548. replace: true,
  2549. link: function(scope, element, attrs, ctrls) {
  2550. var ratingCtrl = ctrls[0], ngModelCtrl = ctrls[1];
  2551. if ( ngModelCtrl ) {
  2552. ratingCtrl.init( ngModelCtrl );
  2553. }
  2554. }
  2555. };
  2556. });
  2557. /**
  2558. * @ngdoc overview
  2559. * @name ui.bootstrap.tabs
  2560. *
  2561. * @description
  2562. * AngularJS version of the tabs directive.
  2563. */
  2564. angular.module('ui.bootstrap.tabs', [])
  2565. .controller('TabsetController', ['$scope', function TabsetCtrl($scope) {
  2566. var ctrl = this,
  2567. tabs = ctrl.tabs = $scope.tabs = [];
  2568. ctrl.select = function(selectedTab) {
  2569. angular.forEach(tabs, function(tab) {
  2570. if (tab.active && tab !== selectedTab) {
  2571. tab.active = false;
  2572. tab.onDeselect();
  2573. }
  2574. });
  2575. selectedTab.active = true;
  2576. selectedTab.onSelect();
  2577. };
  2578. ctrl.addTab = function addTab(tab) {
  2579. tabs.push(tab);
  2580. // we can't run the select function on the first tab
  2581. // since that would select it twice
  2582. if (tabs.length === 1) {
  2583. tab.active = true;
  2584. } else if (tab.active) {
  2585. ctrl.select(tab);
  2586. }
  2587. };
  2588. ctrl.removeTab = function removeTab(tab) {
  2589. var index = tabs.indexOf(tab);
  2590. //Select a new tab if the tab to be removed is selected and not destroyed
  2591. if (tab.active && tabs.length > 1 && !destroyed) {
  2592. //If this is the last tab, select the previous tab. else, the next tab.
  2593. var newActiveIndex = index == tabs.length - 1 ? index - 1 : index + 1;
  2594. ctrl.select(tabs[newActiveIndex]);
  2595. }
  2596. tabs.splice(index, 1);
  2597. };
  2598. var destroyed;
  2599. $scope.$on('$destroy', function() {
  2600. destroyed = true;
  2601. });
  2602. }])
  2603. /**
  2604. * @ngdoc directive
  2605. * @name ui.bootstrap.tabs.directive:tabset
  2606. * @restrict EA
  2607. *
  2608. * @description
  2609. * Tabset is the outer container for the tabs directive
  2610. *
  2611. * @param {boolean=} vertical Whether or not to use vertical styling for the tabs.
  2612. * @param {boolean=} justified Whether or not to use justified styling for the tabs.
  2613. *
  2614. * @example
  2615. <example module="ui.bootstrap">
  2616. <file name="index.html">
  2617. <tabset>
  2618. <tab heading="Tab 1"><b>First</b> Content!</tab>
  2619. <tab heading="Tab 2"><i>Second</i> Content!</tab>
  2620. </tabset>
  2621. <hr />
  2622. <tabset vertical="true">
  2623. <tab heading="Vertical Tab 1"><b>First</b> Vertical Content!</tab>
  2624. <tab heading="Vertical Tab 2"><i>Second</i> Vertical Content!</tab>
  2625. </tabset>
  2626. <tabset justified="true">
  2627. <tab heading="Justified Tab 1"><b>First</b> Justified Content!</tab>
  2628. <tab heading="Justified Tab 2"><i>Second</i> Justified Content!</tab>
  2629. </tabset>
  2630. </file>
  2631. </example>
  2632. */
  2633. .directive('tabset', function() {
  2634. return {
  2635. restrict: 'EA',
  2636. transclude: true,
  2637. replace: true,
  2638. scope: {
  2639. type: '@'
  2640. },
  2641. controller: 'TabsetController',
  2642. templateUrl: 'template/tabs/tabset.html',
  2643. link: function(scope, element, attrs) {
  2644. scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false;
  2645. scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false;
  2646. }
  2647. };
  2648. })
  2649. /**
  2650. * @ngdoc directive
  2651. * @name ui.bootstrap.tabs.directive:tab
  2652. * @restrict EA
  2653. *
  2654. * @param {string=} heading The visible heading, or title, of the tab. Set HTML headings with {@link ui.bootstrap.tabs.directive:tabHeading tabHeading}.
  2655. * @param {string=} select An expression to evaluate when the tab is selected.
  2656. * @param {boolean=} active A binding, telling whether or not this tab is selected.
  2657. * @param {boolean=} disabled A binding, telling whether or not this tab is disabled.
  2658. *
  2659. * @description
  2660. * Creates a tab with a heading and content. Must be placed within a {@link ui.bootstrap.tabs.directive:tabset tabset}.
  2661. *
  2662. * @example
  2663. <example module="ui.bootstrap">
  2664. <file name="index.html">
  2665. <div ng-controller="TabsDemoCtrl">
  2666. <button class="btn btn-small" ng-click="items[0].active = true">
  2667. Select item 1, using active binding
  2668. </button>
  2669. <button class="btn btn-small" ng-click="items[1].disabled = !items[1].disabled">
  2670. Enable/disable item 2, using disabled binding
  2671. </button>
  2672. <br />
  2673. <tabset>
  2674. <tab heading="Tab 1">First Tab</tab>
  2675. <tab select="alertMe()">
  2676. <tab-heading><i class="icon-bell"></i> Alert me!</tab-heading>
  2677. Second Tab, with alert callback and html heading!
  2678. </tab>
  2679. <tab ng-repeat="item in items"
  2680. heading="{{item.title}}"
  2681. disabled="item.disabled"
  2682. active="item.active">
  2683. {{item.content}}
  2684. </tab>
  2685. </tabset>
  2686. </div>
  2687. </file>
  2688. <file name="script.js">
  2689. function TabsDemoCtrl($scope) {
  2690. $scope.items = [
  2691. { title:"Dynamic Title 1", content:"Dynamic Item 0" },
  2692. { title:"Dynamic Title 2", content:"Dynamic Item 1", disabled: true }
  2693. ];
  2694. $scope.alertMe = function() {
  2695. setTimeout(function() {
  2696. alert("You've selected the alert tab!");
  2697. });
  2698. };
  2699. };
  2700. </file>
  2701. </example>
  2702. */
  2703. /**
  2704. * @ngdoc directive
  2705. * @name ui.bootstrap.tabs.directive:tabHeading
  2706. * @restrict EA
  2707. *
  2708. * @description
  2709. * Creates an HTML heading for a {@link ui.bootstrap.tabs.directive:tab tab}. Must be placed as a child of a tab element.
  2710. *
  2711. * @example
  2712. <example module="ui.bootstrap">
  2713. <file name="index.html">
  2714. <tabset>
  2715. <tab>
  2716. <tab-heading><b>HTML</b> in my titles?!</tab-heading>
  2717. And some content, too!
  2718. </tab>
  2719. <tab>
  2720. <tab-heading><i class="icon-heart"></i> Icon heading?!?</tab-heading>
  2721. That's right.
  2722. </tab>
  2723. </tabset>
  2724. </file>
  2725. </example>
  2726. */
  2727. .directive('tab', ['$parse', function($parse) {
  2728. return {
  2729. require: '^tabset',
  2730. restrict: 'EA',
  2731. replace: true,
  2732. templateUrl: 'template/tabs/tab.html',
  2733. transclude: true,
  2734. scope: {
  2735. active: '=?',
  2736. heading: '@',
  2737. onSelect: '&select', //This callback is called in contentHeadingTransclude
  2738. //once it inserts the tab's content into the dom
  2739. onDeselect: '&deselect'
  2740. },
  2741. controller: function() {
  2742. //Empty controller so other directives can require being 'under' a tab
  2743. },
  2744. compile: function(elm, attrs, transclude) {
  2745. return function postLink(scope, elm, attrs, tabsetCtrl) {
  2746. scope.$watch('active', function(active) {
  2747. if (active) {
  2748. tabsetCtrl.select(scope);
  2749. }
  2750. });
  2751. scope.disabled = false;
  2752. if ( attrs.disabled ) {
  2753. scope.$parent.$watch($parse(attrs.disabled), function(value) {
  2754. scope.disabled = !! value;
  2755. });
  2756. }
  2757. scope.select = function() {
  2758. if ( !scope.disabled ) {
  2759. scope.active = true;
  2760. }
  2761. };
  2762. tabsetCtrl.addTab(scope);
  2763. scope.$on('$destroy', function() {
  2764. tabsetCtrl.removeTab(scope);
  2765. });
  2766. //We need to transclude later, once the content container is ready.
  2767. //when this link happens, we're inside a tab heading.
  2768. scope.$transcludeFn = transclude;
  2769. };
  2770. }
  2771. };
  2772. }])
  2773. .directive('tabHeadingTransclude', [function() {
  2774. return {
  2775. restrict: 'A',
  2776. require: '^tab',
  2777. link: function(scope, elm, attrs, tabCtrl) {
  2778. scope.$watch('headingElement', function updateHeadingElement(heading) {
  2779. if (heading) {
  2780. elm.html('');
  2781. elm.append(heading);
  2782. }
  2783. });
  2784. }
  2785. };
  2786. }])
  2787. .directive('tabContentTransclude', function() {
  2788. return {
  2789. restrict: 'A',
  2790. require: '^tabset',
  2791. link: function(scope, elm, attrs) {
  2792. var tab = scope.$eval(attrs.tabContentTransclude);
  2793. //Now our tab is ready to be transcluded: both the tab heading area
  2794. //and the tab content area are loaded. Transclude 'em both.
  2795. tab.$transcludeFn(tab.$parent, function(contents) {
  2796. angular.forEach(contents, function(node) {
  2797. if (isTabHeading(node)) {
  2798. //Let tabHeadingTransclude know.
  2799. tab.headingElement = node;
  2800. } else {
  2801. elm.append(node);
  2802. }
  2803. });
  2804. });
  2805. }
  2806. };
  2807. function isTabHeading(node) {
  2808. return node.tagName && (
  2809. node.hasAttribute('tab-heading') ||
  2810. node.hasAttribute('data-tab-heading') ||
  2811. node.tagName.toLowerCase() === 'tab-heading' ||
  2812. node.tagName.toLowerCase() === 'data-tab-heading'
  2813. );
  2814. }
  2815. })
  2816. ;
  2817. angular.module('ui.bootstrap.timepicker', [])
  2818. .constant('timepickerConfig', {
  2819. hourStep: 1,
  2820. minuteStep: 1,
  2821. showMeridian: true,
  2822. meridians: null,
  2823. readonlyInput: false,
  2824. mousewheel: true
  2825. })
  2826. .controller('TimepickerController', ['$scope', '$attrs', '$parse', '$log', '$locale', 'timepickerConfig', function($scope, $attrs, $parse, $log, $locale, timepickerConfig) {
  2827. var selected = new Date(),
  2828. ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl
  2829. meridians = angular.isDefined($attrs.meridians) ? $scope.$parent.$eval($attrs.meridians) : timepickerConfig.meridians || $locale.DATETIME_FORMATS.AMPMS;
  2830. this.init = function( ngModelCtrl_, inputs ) {
  2831. ngModelCtrl = ngModelCtrl_;
  2832. ngModelCtrl.$render = this.render;
  2833. var hoursInputEl = inputs.eq(0),
  2834. minutesInputEl = inputs.eq(1);
  2835. var mousewheel = angular.isDefined($attrs.mousewheel) ? $scope.$parent.$eval($attrs.mousewheel) : timepickerConfig.mousewheel;
  2836. if ( mousewheel ) {
  2837. this.setupMousewheelEvents( hoursInputEl, minutesInputEl );
  2838. }
  2839. $scope.readonlyInput = angular.isDefined($attrs.readonlyInput) ? $scope.$parent.$eval($attrs.readonlyInput) : timepickerConfig.readonlyInput;
  2840. this.setupInputEvents( hoursInputEl, minutesInputEl );
  2841. };
  2842. var hourStep = timepickerConfig.hourStep;
  2843. if ($attrs.hourStep) {
  2844. $scope.$parent.$watch($parse($attrs.hourStep), function(value) {
  2845. hourStep = parseInt(value, 10);
  2846. });
  2847. }
  2848. var minuteStep = timepickerConfig.minuteStep;
  2849. if ($attrs.minuteStep) {
  2850. $scope.$parent.$watch($parse($attrs.minuteStep), function(value) {
  2851. minuteStep = parseInt(value, 10);
  2852. });
  2853. }
  2854. // 12H / 24H mode
  2855. $scope.showMeridian = timepickerConfig.showMeridian;
  2856. if ($attrs.showMeridian) {
  2857. $scope.$parent.$watch($parse($attrs.showMeridian), function(value) {
  2858. $scope.showMeridian = !!value;
  2859. if ( ngModelCtrl.$error.time ) {
  2860. // Evaluate from template
  2861. var hours = getHoursFromTemplate(), minutes = getMinutesFromTemplate();
  2862. if (angular.isDefined( hours ) && angular.isDefined( minutes )) {
  2863. selected.setHours( hours );
  2864. refresh();
  2865. }
  2866. } else {
  2867. updateTemplate();
  2868. }
  2869. });
  2870. }
  2871. // Get $scope.hours in 24H mode if valid
  2872. function getHoursFromTemplate ( ) {
  2873. var hours = parseInt( $scope.hours, 10 );
  2874. var valid = ( $scope.showMeridian ) ? (hours > 0 && hours < 13) : (hours >= 0 && hours < 24);
  2875. if ( !valid ) {
  2876. return undefined;
  2877. }
  2878. if ( $scope.showMeridian ) {
  2879. if ( hours === 12 ) {
  2880. hours = 0;
  2881. }
  2882. if ( $scope.meridian === meridians[1] ) {
  2883. hours = hours + 12;
  2884. }
  2885. }
  2886. return hours;
  2887. }
  2888. function getMinutesFromTemplate() {
  2889. var minutes = parseInt($scope.minutes, 10);
  2890. return ( minutes >= 0 && minutes < 60 ) ? minutes : undefined;
  2891. }
  2892. function pad( value ) {
  2893. return ( angular.isDefined(value) && value.toString().length < 2 ) ? '0' + value : value;
  2894. }
  2895. // Respond on mousewheel spin
  2896. this.setupMousewheelEvents = function( hoursInputEl, minutesInputEl ) {
  2897. var isScrollingUp = function(e) {
  2898. if (e.originalEvent) {
  2899. e = e.originalEvent;
  2900. }
  2901. //pick correct delta variable depending on event
  2902. var delta = (e.wheelDelta) ? e.wheelDelta : -e.deltaY;
  2903. return (e.detail || delta > 0);
  2904. };
  2905. hoursInputEl.bind('mousewheel wheel', function(e) {
  2906. $scope.$apply( (isScrollingUp(e)) ? $scope.incrementHours() : $scope.decrementHours() );
  2907. e.preventDefault();
  2908. });
  2909. minutesInputEl.bind('mousewheel wheel', function(e) {
  2910. $scope.$apply( (isScrollingUp(e)) ? $scope.incrementMinutes() : $scope.decrementMinutes() );
  2911. e.preventDefault();
  2912. });
  2913. };
  2914. this.setupInputEvents = function( hoursInputEl, minutesInputEl ) {
  2915. if ( $scope.readonlyInput ) {
  2916. $scope.updateHours = angular.noop;
  2917. $scope.updateMinutes = angular.noop;
  2918. return;
  2919. }
  2920. var invalidate = function(invalidHours, invalidMinutes) {
  2921. ngModelCtrl.$setViewValue( null );
  2922. ngModelCtrl.$setValidity('time', false);
  2923. if (angular.isDefined(invalidHours)) {
  2924. $scope.invalidHours = invalidHours;
  2925. }
  2926. if (angular.isDefined(invalidMinutes)) {
  2927. $scope.invalidMinutes = invalidMinutes;
  2928. }
  2929. };
  2930. $scope.updateHours = function() {
  2931. var hours = getHoursFromTemplate();
  2932. if ( angular.isDefined(hours) ) {
  2933. selected.setHours( hours );
  2934. refresh( 'h' );
  2935. } else {
  2936. invalidate(true);
  2937. }
  2938. };
  2939. hoursInputEl.bind('blur', function(e) {
  2940. if ( !$scope.invalidHours && $scope.hours < 10) {
  2941. $scope.$apply( function() {
  2942. $scope.hours = pad( $scope.hours );
  2943. });
  2944. }
  2945. });
  2946. $scope.updateMinutes = function() {
  2947. var minutes = getMinutesFromTemplate();
  2948. if ( angular.isDefined(minutes) ) {
  2949. selected.setMinutes( minutes );
  2950. refresh( 'm' );
  2951. } else {
  2952. invalidate(undefined, true);
  2953. }
  2954. };
  2955. minutesInputEl.bind('blur', function(e) {
  2956. if ( !$scope.invalidMinutes && $scope.minutes < 10 ) {
  2957. $scope.$apply( function() {
  2958. $scope.minutes = pad( $scope.minutes );
  2959. });
  2960. }
  2961. });
  2962. };
  2963. this.render = function() {
  2964. var date = ngModelCtrl.$modelValue ? new Date( ngModelCtrl.$modelValue ) : null;
  2965. if ( isNaN(date) ) {
  2966. ngModelCtrl.$setValidity('time', false);
  2967. $log.error('Timepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');
  2968. } else {
  2969. if ( date ) {
  2970. selected = date;
  2971. }
  2972. makeValid();
  2973. updateTemplate();
  2974. }
  2975. };
  2976. // Call internally when we know that model is valid.
  2977. function refresh( keyboardChange ) {
  2978. makeValid();
  2979. ngModelCtrl.$setViewValue( new Date(selected) );
  2980. updateTemplate( keyboardChange );
  2981. }
  2982. function makeValid() {
  2983. ngModelCtrl.$setValidity('time', true);
  2984. $scope.invalidHours = false;
  2985. $scope.invalidMinutes = false;
  2986. }
  2987. function updateTemplate( keyboardChange ) {
  2988. var hours = selected.getHours(), minutes = selected.getMinutes();
  2989. if ( $scope.showMeridian ) {
  2990. hours = ( hours === 0 || hours === 12 ) ? 12 : hours % 12; // Convert 24 to 12 hour system
  2991. }
  2992. $scope.hours = keyboardChange === 'h' ? hours : pad(hours);
  2993. $scope.minutes = keyboardChange === 'm' ? minutes : pad(minutes);
  2994. $scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1];
  2995. }
  2996. function addMinutes( minutes ) {
  2997. var dt = new Date( selected.getTime() + minutes * 60000 );
  2998. selected.setHours( dt.getHours(), dt.getMinutes() );
  2999. refresh();
  3000. }
  3001. $scope.incrementHours = function() {
  3002. addMinutes( hourStep * 60 );
  3003. };
  3004. $scope.decrementHours = function() {
  3005. addMinutes( - hourStep * 60 );
  3006. };
  3007. $scope.incrementMinutes = function() {
  3008. addMinutes( minuteStep );
  3009. };
  3010. $scope.decrementMinutes = function() {
  3011. addMinutes( - minuteStep );
  3012. };
  3013. $scope.toggleMeridian = function() {
  3014. addMinutes( 12 * 60 * (( selected.getHours() < 12 ) ? 1 : -1) );
  3015. };
  3016. }])
  3017. .directive('timepicker', function () {
  3018. return {
  3019. restrict: 'EA',
  3020. require: ['timepicker', '?^ngModel'],
  3021. controller:'TimepickerController',
  3022. replace: true,
  3023. scope: {},
  3024. templateUrl: 'template/timepicker/timepicker.html',
  3025. link: function(scope, element, attrs, ctrls) {
  3026. var timepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];
  3027. if ( ngModelCtrl ) {
  3028. timepickerCtrl.init( ngModelCtrl, element.find('input') );
  3029. }
  3030. }
  3031. };
  3032. });
  3033. angular.module('ui.bootstrap.typeahead', ['ui.bootstrap.position', 'ui.bootstrap.bindHtml'])
  3034. /**
  3035. * A helper service that can parse typeahead's syntax (string provided by users)
  3036. * Extracted to a separate service for ease of unit testing
  3037. */
  3038. .factory('typeaheadParser', ['$parse', function ($parse) {
  3039. // 00000111000000000000022200000000000000003333333333333330000000000044000
  3040. var TYPEAHEAD_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+([\s\S]+?)$/;
  3041. return {
  3042. parse:function (input) {
  3043. var match = input.match(TYPEAHEAD_REGEXP);
  3044. if (!match) {
  3045. throw new Error(
  3046. 'Expected typeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_"' +
  3047. ' but got "' + input + '".');
  3048. }
  3049. return {
  3050. itemName:match[3],
  3051. source:$parse(match[4]),
  3052. viewMapper:$parse(match[2] || match[1]),
  3053. modelMapper:$parse(match[1])
  3054. };
  3055. }
  3056. };
  3057. }])
  3058. .directive('typeahead', ['$compile', '$parse', '$q', '$timeout', '$document', '$position', 'typeaheadParser',
  3059. function ($compile, $parse, $q, $timeout, $document, $position, typeaheadParser) {
  3060. var HOT_KEYS = [9, 13, 27, 38, 40];
  3061. return {
  3062. require:'ngModel',
  3063. link:function (originalScope, element, attrs, modelCtrl) {
  3064. //SUPPORTED ATTRIBUTES (OPTIONS)
  3065. //minimal no of characters that needs to be entered before typeahead kicks-in
  3066. var minSearch = originalScope.$eval(attrs.typeaheadMinLength) || 1;
  3067. //minimal wait time after last character typed before typehead kicks-in
  3068. var waitTime = originalScope.$eval(attrs.typeaheadWaitMs) || 0;
  3069. //should it restrict model values to the ones selected from the popup only?
  3070. var isEditable = originalScope.$eval(attrs.typeaheadEditable) !== false;
  3071. //binding to a variable that indicates if matches are being retrieved asynchronously
  3072. var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop;
  3073. //a callback executed when a match is selected
  3074. var onSelectCallback = $parse(attrs.typeaheadOnSelect);
  3075. var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined;
  3076. var appendToBody = attrs.typeaheadAppendToBody ? originalScope.$eval(attrs.typeaheadAppendToBody) : false;
  3077. var focusFirst = originalScope.$eval(attrs.typeaheadFocusFirst) !== false;
  3078. //INTERNAL VARIABLES
  3079. //model setter executed upon match selection
  3080. var $setModelValue = $parse(attrs.ngModel).assign;
  3081. //expressions used by typeahead
  3082. var parserResult = typeaheadParser.parse(attrs.typeahead);
  3083. var hasFocus;
  3084. //create a child scope for the typeahead directive so we are not polluting original scope
  3085. //with typeahead-specific data (matches, query etc.)
  3086. var scope = originalScope.$new();
  3087. originalScope.$on('$destroy', function(){
  3088. scope.$destroy();
  3089. });
  3090. // WAI-ARIA
  3091. var popupId = 'typeahead-' + scope.$id + '-' + Math.floor(Math.random() * 10000);
  3092. element.attr({
  3093. 'aria-autocomplete': 'list',
  3094. 'aria-expanded': false,
  3095. 'aria-owns': popupId
  3096. });
  3097. //pop-up element used to display matches
  3098. var popUpEl = angular.element('<div typeahead-popup></div>');
  3099. popUpEl.attr({
  3100. id: popupId,
  3101. matches: 'matches',
  3102. active: 'activeIdx',
  3103. select: 'select(activeIdx)',
  3104. query: 'query',
  3105. position: 'position'
  3106. });
  3107. //custom item template
  3108. if (angular.isDefined(attrs.typeaheadTemplateUrl)) {
  3109. popUpEl.attr('template-url', attrs.typeaheadTemplateUrl);
  3110. }
  3111. var resetMatches = function() {
  3112. scope.matches = [];
  3113. scope.activeIdx = -1;
  3114. element.attr('aria-expanded', false);
  3115. };
  3116. var getMatchId = function(index) {
  3117. return popupId + '-option-' + index;
  3118. };
  3119. // Indicate that the specified match is the active (pre-selected) item in the list owned by this typeahead.
  3120. // This attribute is added or removed automatically when the `activeIdx` changes.
  3121. scope.$watch('activeIdx', function(index) {
  3122. if (index < 0) {
  3123. element.removeAttr('aria-activedescendant');
  3124. } else {
  3125. element.attr('aria-activedescendant', getMatchId(index));
  3126. }
  3127. });
  3128. var getMatchesAsync = function(inputValue) {
  3129. var locals = {$viewValue: inputValue};
  3130. isLoadingSetter(originalScope, true);
  3131. $q.when(parserResult.source(originalScope, locals)).then(function(matches) {
  3132. //it might happen that several async queries were in progress if a user were typing fast
  3133. //but we are interested only in responses that correspond to the current view value
  3134. var onCurrentRequest = (inputValue === modelCtrl.$viewValue);
  3135. if (onCurrentRequest && hasFocus) {
  3136. if (matches.length > 0) {
  3137. scope.activeIdx = focusFirst ? 0 : -1;
  3138. scope.matches.length = 0;
  3139. //transform labels
  3140. for(var i=0; i<matches.length; i++) {
  3141. locals[parserResult.itemName] = matches[i];
  3142. scope.matches.push({
  3143. id: getMatchId(i),
  3144. label: parserResult.viewMapper(scope, locals),
  3145. model: matches[i]
  3146. });
  3147. }
  3148. scope.query = inputValue;
  3149. //position pop-up with matches - we need to re-calculate its position each time we are opening a window
  3150. //with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page
  3151. //due to other elements being rendered
  3152. scope.position = appendToBody ? $position.offset(element) : $position.position(element);
  3153. scope.position.top = scope.position.top + element.prop('offsetHeight');
  3154. element.attr('aria-expanded', true);
  3155. } else {
  3156. resetMatches();
  3157. }
  3158. }
  3159. if (onCurrentRequest) {
  3160. isLoadingSetter(originalScope, false);
  3161. }
  3162. }, function(){
  3163. resetMatches();
  3164. isLoadingSetter(originalScope, false);
  3165. });
  3166. };
  3167. resetMatches();
  3168. //we need to propagate user's query so we can higlight matches
  3169. scope.query = undefined;
  3170. //Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later
  3171. var timeoutPromise;
  3172. var scheduleSearchWithTimeout = function(inputValue) {
  3173. timeoutPromise = $timeout(function () {
  3174. getMatchesAsync(inputValue);
  3175. }, waitTime);
  3176. };
  3177. var cancelPreviousTimeout = function() {
  3178. if (timeoutPromise) {
  3179. $timeout.cancel(timeoutPromise);
  3180. }
  3181. };
  3182. //plug into $parsers pipeline to open a typeahead on view changes initiated from DOM
  3183. //$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue
  3184. modelCtrl.$parsers.unshift(function (inputValue) {
  3185. hasFocus = true;
  3186. if (inputValue && inputValue.length >= minSearch) {
  3187. if (waitTime > 0) {
  3188. cancelPreviousTimeout();
  3189. scheduleSearchWithTimeout(inputValue);
  3190. } else {
  3191. getMatchesAsync(inputValue);
  3192. }
  3193. } else {
  3194. isLoadingSetter(originalScope, false);
  3195. cancelPreviousTimeout();
  3196. resetMatches();
  3197. }
  3198. if (isEditable) {
  3199. return inputValue;
  3200. } else {
  3201. if (!inputValue) {
  3202. // Reset in case user had typed something previously.
  3203. modelCtrl.$setValidity('editable', true);
  3204. return inputValue;
  3205. } else {
  3206. modelCtrl.$setValidity('editable', false);
  3207. return undefined;
  3208. }
  3209. }
  3210. });
  3211. modelCtrl.$formatters.push(function (modelValue) {
  3212. var candidateViewValue, emptyViewValue;
  3213. var locals = {};
  3214. if (inputFormatter) {
  3215. locals.$model = modelValue;
  3216. return inputFormatter(originalScope, locals);
  3217. } else {
  3218. //it might happen that we don't have enough info to properly render input value
  3219. //we need to check for this situation and simply return model value if we can't apply custom formatting
  3220. locals[parserResult.itemName] = modelValue;
  3221. candidateViewValue = parserResult.viewMapper(originalScope, locals);
  3222. locals[parserResult.itemName] = undefined;
  3223. emptyViewValue = parserResult.viewMapper(originalScope, locals);
  3224. return candidateViewValue!== emptyViewValue ? candidateViewValue : modelValue;
  3225. }
  3226. });
  3227. scope.select = function (activeIdx) {
  3228. //called from within the $digest() cycle
  3229. var locals = {};
  3230. var model, item;
  3231. locals[parserResult.itemName] = item = scope.matches[activeIdx].model;
  3232. model = parserResult.modelMapper(originalScope, locals);
  3233. $setModelValue(originalScope, model);
  3234. modelCtrl.$setValidity('editable', true);
  3235. onSelectCallback(originalScope, {
  3236. $item: item,
  3237. $model: model,
  3238. $label: parserResult.viewMapper(originalScope, locals)
  3239. });
  3240. resetMatches();
  3241. //return focus to the input element if a match was selected via a mouse click event
  3242. // use timeout to avoid $rootScope:inprog error
  3243. $timeout(function() { element[0].focus(); }, 0, false);
  3244. };
  3245. //bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27)
  3246. element.bind('keydown', function (evt) {
  3247. //typeahead is open and an "interesting" key was pressed
  3248. if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) {
  3249. return;
  3250. }
  3251. // if there's nothing selected (i.e. focusFirst) and enter is hit, don't do anything
  3252. if (scope.activeIdx == -1 && (evt.which === 13 || evt.which === 9)) {
  3253. return;
  3254. }
  3255. evt.preventDefault();
  3256. if (evt.which === 40) {
  3257. scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length;
  3258. scope.$digest();
  3259. } else if (evt.which === 38) {
  3260. scope.activeIdx = (scope.activeIdx > 0 ? scope.activeIdx : scope.matches.length) - 1;
  3261. scope.$digest();
  3262. } else if (evt.which === 13 || evt.which === 9) {
  3263. scope.$apply(function () {
  3264. scope.select(scope.activeIdx);
  3265. });
  3266. } else if (evt.which === 27) {
  3267. evt.stopPropagation();
  3268. resetMatches();
  3269. scope.$digest();
  3270. }
  3271. });
  3272. element.bind('blur', function (evt) {
  3273. hasFocus = false;
  3274. });
  3275. // Keep reference to click handler to unbind it.
  3276. var dismissClickHandler = function (evt) {
  3277. if (element[0] !== evt.target) {
  3278. resetMatches();
  3279. scope.$digest();
  3280. }
  3281. };
  3282. $document.bind('click', dismissClickHandler);
  3283. originalScope.$on('$destroy', function(){
  3284. $document.unbind('click', dismissClickHandler);
  3285. if (appendToBody) {
  3286. $popup.remove();
  3287. }
  3288. });
  3289. var $popup = $compile(popUpEl)(scope);
  3290. if (appendToBody) {
  3291. $document.find('body').append($popup);
  3292. } else {
  3293. element.after($popup);
  3294. }
  3295. }
  3296. };
  3297. }])
  3298. .directive('typeaheadPopup', function () {
  3299. return {
  3300. restrict:'EA',
  3301. scope:{
  3302. matches:'=',
  3303. query:'=',
  3304. active:'=',
  3305. position:'=',
  3306. select:'&'
  3307. },
  3308. replace:true,
  3309. templateUrl:'template/typeahead/typeahead-popup.html',
  3310. link:function (scope, element, attrs) {
  3311. scope.templateUrl = attrs.templateUrl;
  3312. scope.isOpen = function () {
  3313. return scope.matches.length > 0;
  3314. };
  3315. scope.isActive = function (matchIdx) {
  3316. return scope.active == matchIdx;
  3317. };
  3318. scope.selectActive = function (matchIdx) {
  3319. scope.active = matchIdx;
  3320. };
  3321. scope.selectMatch = function (activeIdx) {
  3322. scope.select({activeIdx:activeIdx});
  3323. };
  3324. }
  3325. };
  3326. })
  3327. .directive('typeaheadMatch', ['$http', '$templateCache', '$compile', '$parse', function ($http, $templateCache, $compile, $parse) {
  3328. return {
  3329. restrict:'EA',
  3330. scope:{
  3331. index:'=',
  3332. match:'=',
  3333. query:'='
  3334. },
  3335. link:function (scope, element, attrs) {
  3336. var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'template/typeahead/typeahead-match.html';
  3337. $http.get(tplUrl, {cache: $templateCache}).success(function(tplContent){
  3338. element.replaceWith($compile(tplContent.trim())(scope));
  3339. });
  3340. }
  3341. };
  3342. }])
  3343. .filter('typeaheadHighlight', function() {
  3344. function escapeRegexp(queryToEscape) {
  3345. return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
  3346. }
  3347. return function(matchItem, query) {
  3348. return query ? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem;
  3349. };
  3350. });