ui-bootstrap.js 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900
  1. /*
  2. * angular-ui-bootstrap
  3. * http://angular-ui.github.io/bootstrap/
  4. * Version: 0.12.1 - 2015-02-20
  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. // Inner change
  1326. scope.dateSelection = function(dt) {
  1327. if (angular.isDefined(dt)) {
  1328. scope.date = dt;
  1329. }
  1330. ngModel.$setViewValue(scope.date);
  1331. ngModel.$render();
  1332. if ( closeOnDateSelection ) {
  1333. scope.isOpen = false;
  1334. element[0].focus();
  1335. }
  1336. };
  1337. element.bind('input change keyup', function() {
  1338. scope.$apply(function() {
  1339. scope.date = ngModel.$modelValue;
  1340. });
  1341. });
  1342. // Outter change
  1343. ngModel.$render = function() {
  1344. var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : '';
  1345. element.val(date);
  1346. scope.date = parseDate( ngModel.$modelValue );
  1347. };
  1348. var documentClickBind = function(event) {
  1349. if (scope.isOpen && event.target !== element[0]) {
  1350. scope.$apply(function() {
  1351. scope.isOpen = false;
  1352. });
  1353. }
  1354. };
  1355. var keydown = function(evt, noApply) {
  1356. scope.keydown(evt);
  1357. };
  1358. element.bind('keydown', keydown);
  1359. scope.keydown = function(evt) {
  1360. if (evt.which === 27) {
  1361. evt.preventDefault();
  1362. evt.stopPropagation();
  1363. scope.close();
  1364. } else if (evt.which === 40 && !scope.isOpen) {
  1365. scope.isOpen = true;
  1366. }
  1367. };
  1368. scope.$watch('isOpen', function(value) {
  1369. if (value) {
  1370. scope.$broadcast('datepicker.focus');
  1371. scope.position = appendToBody ? $position.offset(element) : $position.position(element);
  1372. scope.position.top = scope.position.top + element.prop('offsetHeight');
  1373. $document.bind('click', documentClickBind);
  1374. } else {
  1375. $document.unbind('click', documentClickBind);
  1376. }
  1377. });
  1378. scope.select = function( date ) {
  1379. if (date === 'today') {
  1380. var today = new Date();
  1381. if (angular.isDate(ngModel.$modelValue)) {
  1382. date = new Date(ngModel.$modelValue);
  1383. date.setFullYear(today.getFullYear(), today.getMonth(), today.getDate());
  1384. } else {
  1385. date = new Date(today.setHours(0, 0, 0, 0));
  1386. }
  1387. }
  1388. scope.dateSelection( date );
  1389. };
  1390. scope.close = function() {
  1391. scope.isOpen = false;
  1392. element[0].focus();
  1393. };
  1394. var $popup = $compile(popupEl)(scope);
  1395. // Prevent jQuery cache memory leak (template is now redundant after linking)
  1396. popupEl.remove();
  1397. if ( appendToBody ) {
  1398. $document.find('body').append($popup);
  1399. } else {
  1400. element.after($popup);
  1401. }
  1402. scope.$on('$destroy', function() {
  1403. $popup.remove();
  1404. element.unbind('keydown', keydown);
  1405. $document.unbind('click', documentClickBind);
  1406. });
  1407. }
  1408. };
  1409. }])
  1410. .directive('datepickerPopupWrap', function() {
  1411. return {
  1412. restrict:'EA',
  1413. replace: true,
  1414. transclude: true,
  1415. templateUrl: 'template/datepicker/popup.html',
  1416. link:function (scope, element, attrs) {
  1417. element.bind('click', function(event) {
  1418. event.preventDefault();
  1419. event.stopPropagation();
  1420. });
  1421. }
  1422. };
  1423. });
  1424. angular.module('ui.bootstrap.dropdown', [])
  1425. .constant('dropdownConfig', {
  1426. openClass: 'open'
  1427. })
  1428. .service('dropdownService', ['$document', function($document) {
  1429. var openScope = null;
  1430. this.open = function( dropdownScope ) {
  1431. if ( !openScope ) {
  1432. $document.bind('click', closeDropdown);
  1433. $document.bind('keydown', escapeKeyBind);
  1434. }
  1435. if ( openScope && openScope !== dropdownScope ) {
  1436. openScope.isOpen = false;
  1437. }
  1438. openScope = dropdownScope;
  1439. };
  1440. this.close = function( dropdownScope ) {
  1441. if ( openScope === dropdownScope ) {
  1442. openScope = null;
  1443. $document.unbind('click', closeDropdown);
  1444. $document.unbind('keydown', escapeKeyBind);
  1445. }
  1446. };
  1447. var closeDropdown = function( evt ) {
  1448. // This method may still be called during the same mouse event that
  1449. // unbound this event handler. So check openScope before proceeding.
  1450. if (!openScope) { return; }
  1451. var toggleElement = openScope.getToggleElement();
  1452. if ( evt && toggleElement && toggleElement[0].contains(evt.target) ) {
  1453. return;
  1454. }
  1455. openScope.$apply(function() {
  1456. openScope.isOpen = false;
  1457. });
  1458. };
  1459. var escapeKeyBind = function( evt ) {
  1460. if ( evt.which === 27 ) {
  1461. openScope.focusToggleElement();
  1462. closeDropdown();
  1463. }
  1464. };
  1465. }])
  1466. .controller('DropdownController', ['$scope', '$attrs', '$parse', 'dropdownConfig', 'dropdownService', '$animate', function($scope, $attrs, $parse, dropdownConfig, dropdownService, $animate) {
  1467. var self = this,
  1468. scope = $scope.$new(), // create a child scope so we are not polluting original one
  1469. openClass = dropdownConfig.openClass,
  1470. getIsOpen,
  1471. setIsOpen = angular.noop,
  1472. toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop;
  1473. this.init = function( element ) {
  1474. self.$element = element;
  1475. if ( $attrs.isOpen ) {
  1476. getIsOpen = $parse($attrs.isOpen);
  1477. setIsOpen = getIsOpen.assign;
  1478. $scope.$watch(getIsOpen, function(value) {
  1479. scope.isOpen = !!value;
  1480. });
  1481. }
  1482. };
  1483. this.toggle = function( open ) {
  1484. return scope.isOpen = arguments.length ? !!open : !scope.isOpen;
  1485. };
  1486. // Allow other directives to watch status
  1487. this.isOpen = function() {
  1488. return scope.isOpen;
  1489. };
  1490. scope.getToggleElement = function() {
  1491. return self.toggleElement;
  1492. };
  1493. scope.focusToggleElement = function() {
  1494. if ( self.toggleElement ) {
  1495. self.toggleElement[0].focus();
  1496. }
  1497. };
  1498. scope.$watch('isOpen', function( isOpen, wasOpen ) {
  1499. $animate[isOpen ? 'addClass' : 'removeClass'](self.$element, openClass);
  1500. if ( isOpen ) {
  1501. scope.focusToggleElement();
  1502. dropdownService.open( scope );
  1503. } else {
  1504. dropdownService.close( scope );
  1505. }
  1506. setIsOpen($scope, isOpen);
  1507. if (angular.isDefined(isOpen) && isOpen !== wasOpen) {
  1508. toggleInvoker($scope, { open: !!isOpen });
  1509. }
  1510. });
  1511. $scope.$on('$locationChangeSuccess', function() {
  1512. scope.isOpen = false;
  1513. });
  1514. $scope.$on('$destroy', function() {
  1515. scope.$destroy();
  1516. });
  1517. }])
  1518. .directive('dropdown', function() {
  1519. return {
  1520. controller: 'DropdownController',
  1521. link: function(scope, element, attrs, dropdownCtrl) {
  1522. dropdownCtrl.init( element );
  1523. }
  1524. };
  1525. })
  1526. .directive('dropdownToggle', function() {
  1527. return {
  1528. require: '?^dropdown',
  1529. link: function(scope, element, attrs, dropdownCtrl) {
  1530. if ( !dropdownCtrl ) {
  1531. return;
  1532. }
  1533. dropdownCtrl.toggleElement = element;
  1534. var toggleDropdown = function(event) {
  1535. event.preventDefault();
  1536. if ( !element.hasClass('disabled') && !attrs.disabled ) {
  1537. scope.$apply(function() {
  1538. dropdownCtrl.toggle();
  1539. });
  1540. }
  1541. };
  1542. element.bind('click', toggleDropdown);
  1543. // WAI-ARIA
  1544. element.attr({ 'aria-haspopup': true, 'aria-expanded': false });
  1545. scope.$watch(dropdownCtrl.isOpen, function( isOpen ) {
  1546. element.attr('aria-expanded', !!isOpen);
  1547. });
  1548. scope.$on('$destroy', function() {
  1549. element.unbind('click', toggleDropdown);
  1550. });
  1551. }
  1552. };
  1553. });
  1554. angular.module('ui.bootstrap.modal', ['ui.bootstrap.transition'])
  1555. /**
  1556. * A helper, internal data structure that acts as a map but also allows getting / removing
  1557. * elements in the LIFO order
  1558. */
  1559. .factory('$$stackedMap', function () {
  1560. return {
  1561. createNew: function () {
  1562. var stack = [];
  1563. return {
  1564. add: function (key, value) {
  1565. stack.push({
  1566. key: key,
  1567. value: value
  1568. });
  1569. },
  1570. get: function (key) {
  1571. for (var i = 0; i < stack.length; i++) {
  1572. if (key == stack[i].key) {
  1573. return stack[i];
  1574. }
  1575. }
  1576. },
  1577. keys: function() {
  1578. var keys = [];
  1579. for (var i = 0; i < stack.length; i++) {
  1580. keys.push(stack[i].key);
  1581. }
  1582. return keys;
  1583. },
  1584. top: function () {
  1585. return stack[stack.length - 1];
  1586. },
  1587. remove: function (key) {
  1588. var idx = -1;
  1589. for (var i = 0; i < stack.length; i++) {
  1590. if (key == stack[i].key) {
  1591. idx = i;
  1592. break;
  1593. }
  1594. }
  1595. return stack.splice(idx, 1)[0];
  1596. },
  1597. removeTop: function () {
  1598. return stack.splice(stack.length - 1, 1)[0];
  1599. },
  1600. length: function () {
  1601. return stack.length;
  1602. }
  1603. };
  1604. }
  1605. };
  1606. })
  1607. /**
  1608. * A helper directive for the $modal service. It creates a backdrop element.
  1609. */
  1610. .directive('modalBackdrop', ['$timeout', function ($timeout) {
  1611. return {
  1612. restrict: 'EA',
  1613. replace: true,
  1614. templateUrl: 'template/modal/backdrop.html',
  1615. link: function (scope, element, attrs) {
  1616. scope.backdropClass = attrs.backdropClass || '';
  1617. scope.animate = false;
  1618. //trigger CSS transitions
  1619. $timeout(function () {
  1620. scope.animate = true;
  1621. });
  1622. }
  1623. };
  1624. }])
  1625. .directive('modalWindow', ['$modalStack', '$timeout', function ($modalStack, $timeout) {
  1626. return {
  1627. restrict: 'EA',
  1628. scope: {
  1629. index: '@',
  1630. animate: '='
  1631. },
  1632. replace: true,
  1633. transclude: true,
  1634. templateUrl: function(tElement, tAttrs) {
  1635. return tAttrs.templateUrl || 'template/modal/window.html';
  1636. },
  1637. link: function (scope, element, attrs) {
  1638. element.addClass(attrs.windowClass || '');
  1639. scope.size = attrs.size;
  1640. $timeout(function () {
  1641. // trigger CSS transitions
  1642. scope.animate = true;
  1643. /**
  1644. * Auto-focusing of a freshly-opened modal element causes any child elements
  1645. * with the autofocus attribute to lose focus. This is an issue on touch
  1646. * based devices which will show and then hide the onscreen keyboard.
  1647. * Attempts to refocus the autofocus element via JavaScript will not reopen
  1648. * the onscreen keyboard. Fixed by updated the focusing logic to only autofocus
  1649. * the modal element if the modal does not contain an autofocus element.
  1650. */
  1651. if (!element[0].querySelectorAll('[autofocus]').length) {
  1652. element[0].focus();
  1653. }
  1654. });
  1655. scope.close = function (evt) {
  1656. var modal = $modalStack.getTop();
  1657. if (modal && modal.value.backdrop && modal.value.backdrop != 'static' && (evt.target === evt.currentTarget)) {
  1658. evt.preventDefault();
  1659. evt.stopPropagation();
  1660. $modalStack.dismiss(modal.key, 'backdrop click');
  1661. }
  1662. };
  1663. }
  1664. };
  1665. }])
  1666. .directive('modalTransclude', function () {
  1667. return {
  1668. link: function($scope, $element, $attrs, controller, $transclude) {
  1669. $transclude($scope.$parent, function(clone) {
  1670. $element.empty();
  1671. $element.append(clone);
  1672. });
  1673. }
  1674. };
  1675. })
  1676. .factory('$modalStack', ['$transition', '$timeout', '$document', '$compile', '$rootScope', '$$stackedMap',
  1677. function ($transition, $timeout, $document, $compile, $rootScope, $$stackedMap) {
  1678. var OPENED_MODAL_CLASS = 'modal-open';
  1679. var backdropDomEl, backdropScope;
  1680. var openedWindows = $$stackedMap.createNew();
  1681. var $modalStack = {};
  1682. function backdropIndex() {
  1683. var topBackdropIndex = -1;
  1684. var opened = openedWindows.keys();
  1685. for (var i = 0; i < opened.length; i++) {
  1686. if (openedWindows.get(opened[i]).value.backdrop) {
  1687. topBackdropIndex = i;
  1688. }
  1689. }
  1690. return topBackdropIndex;
  1691. }
  1692. $rootScope.$watch(backdropIndex, function(newBackdropIndex){
  1693. if (backdropScope) {
  1694. backdropScope.index = newBackdropIndex;
  1695. }
  1696. });
  1697. function removeModalWindow(modalInstance) {
  1698. var body = $document.find('body').eq(0);
  1699. var modalWindow = openedWindows.get(modalInstance).value;
  1700. //clean up the stack
  1701. openedWindows.remove(modalInstance);
  1702. //remove window DOM element
  1703. removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, 300, function() {
  1704. modalWindow.modalScope.$destroy();
  1705. body.toggleClass(OPENED_MODAL_CLASS, openedWindows.length() > 0);
  1706. checkRemoveBackdrop();
  1707. });
  1708. }
  1709. function checkRemoveBackdrop() {
  1710. //remove backdrop if no longer needed
  1711. if (backdropDomEl && backdropIndex() == -1) {
  1712. var backdropScopeRef = backdropScope;
  1713. removeAfterAnimate(backdropDomEl, backdropScope, 150, function () {
  1714. backdropScopeRef.$destroy();
  1715. backdropScopeRef = null;
  1716. });
  1717. backdropDomEl = undefined;
  1718. backdropScope = undefined;
  1719. }
  1720. }
  1721. function removeAfterAnimate(domEl, scope, emulateTime, done) {
  1722. // Closing animation
  1723. scope.animate = false;
  1724. var transitionEndEventName = $transition.transitionEndEventName;
  1725. if (transitionEndEventName) {
  1726. // transition out
  1727. var timeout = $timeout(afterAnimating, emulateTime);
  1728. domEl.bind(transitionEndEventName, function () {
  1729. $timeout.cancel(timeout);
  1730. afterAnimating();
  1731. scope.$apply();
  1732. });
  1733. } else {
  1734. // Ensure this call is async
  1735. $timeout(afterAnimating);
  1736. }
  1737. function afterAnimating() {
  1738. if (afterAnimating.done) {
  1739. return;
  1740. }
  1741. afterAnimating.done = true;
  1742. domEl.remove();
  1743. if (done) {
  1744. done();
  1745. }
  1746. }
  1747. }
  1748. $document.bind('keydown', function (evt) {
  1749. var modal;
  1750. if (evt.which === 27) {
  1751. modal = openedWindows.top();
  1752. if (modal && modal.value.keyboard) {
  1753. evt.preventDefault();
  1754. $rootScope.$apply(function () {
  1755. $modalStack.dismiss(modal.key, 'escape key press');
  1756. });
  1757. }
  1758. }
  1759. });
  1760. $modalStack.open = function (modalInstance, modal) {
  1761. openedWindows.add(modalInstance, {
  1762. deferred: modal.deferred,
  1763. modalScope: modal.scope,
  1764. backdrop: modal.backdrop,
  1765. keyboard: modal.keyboard
  1766. });
  1767. var body = $document.find('body').eq(0),
  1768. currBackdropIndex = backdropIndex();
  1769. if (currBackdropIndex >= 0 && !backdropDomEl) {
  1770. backdropScope = $rootScope.$new(true);
  1771. backdropScope.index = currBackdropIndex;
  1772. var angularBackgroundDomEl = angular.element('<div modal-backdrop></div>');
  1773. angularBackgroundDomEl.attr('backdrop-class', modal.backdropClass);
  1774. backdropDomEl = $compile(angularBackgroundDomEl)(backdropScope);
  1775. body.append(backdropDomEl);
  1776. }
  1777. var angularDomEl = angular.element('<div modal-window></div>');
  1778. angularDomEl.attr({
  1779. 'template-url': modal.windowTemplateUrl,
  1780. 'window-class': modal.windowClass,
  1781. 'size': modal.size,
  1782. 'index': openedWindows.length() - 1,
  1783. 'animate': 'animate'
  1784. }).html(modal.content);
  1785. var modalDomEl = $compile(angularDomEl)(modal.scope);
  1786. openedWindows.top().value.modalDomEl = modalDomEl;
  1787. body.append(modalDomEl);
  1788. body.addClass(OPENED_MODAL_CLASS);
  1789. };
  1790. $modalStack.close = function (modalInstance, result) {
  1791. var modalWindow = openedWindows.get(modalInstance);
  1792. if (modalWindow) {
  1793. modalWindow.value.deferred.resolve(result);
  1794. removeModalWindow(modalInstance);
  1795. }
  1796. };
  1797. $modalStack.dismiss = function (modalInstance, reason) {
  1798. var modalWindow = openedWindows.get(modalInstance);
  1799. if (modalWindow) {
  1800. modalWindow.value.deferred.reject(reason);
  1801. removeModalWindow(modalInstance);
  1802. }
  1803. };
  1804. $modalStack.dismissAll = function (reason) {
  1805. var topModal = this.getTop();
  1806. while (topModal) {
  1807. this.dismiss(topModal.key, reason);
  1808. topModal = this.getTop();
  1809. }
  1810. };
  1811. $modalStack.getTop = function () {
  1812. return openedWindows.top();
  1813. };
  1814. return $modalStack;
  1815. }])
  1816. .provider('$modal', function () {
  1817. var $modalProvider = {
  1818. options: {
  1819. backdrop: true, //can be also false or 'static'
  1820. keyboard: true
  1821. },
  1822. $get: ['$injector', '$rootScope', '$q', '$http', '$templateCache', '$controller', '$modalStack',
  1823. function ($injector, $rootScope, $q, $http, $templateCache, $controller, $modalStack) {
  1824. var $modal = {};
  1825. function getTemplatePromise(options) {
  1826. return options.template ? $q.when(options.template) :
  1827. $http.get(angular.isFunction(options.templateUrl) ? (options.templateUrl)() : options.templateUrl,
  1828. {cache: $templateCache}).then(function (result) {
  1829. return result.data;
  1830. });
  1831. }
  1832. function getResolvePromises(resolves) {
  1833. var promisesArr = [];
  1834. angular.forEach(resolves, function (value) {
  1835. if (angular.isFunction(value) || angular.isArray(value)) {
  1836. promisesArr.push($q.when($injector.invoke(value)));
  1837. }
  1838. });
  1839. return promisesArr;
  1840. }
  1841. $modal.open = function (modalOptions) {
  1842. var modalResultDeferred = $q.defer();
  1843. var modalOpenedDeferred = $q.defer();
  1844. //prepare an instance of a modal to be injected into controllers and returned to a caller
  1845. var modalInstance = {
  1846. result: modalResultDeferred.promise,
  1847. opened: modalOpenedDeferred.promise,
  1848. close: function (result) {
  1849. $modalStack.close(modalInstance, result);
  1850. },
  1851. dismiss: function (reason) {
  1852. $modalStack.dismiss(modalInstance, reason);
  1853. }
  1854. };
  1855. //merge and clean up options
  1856. modalOptions = angular.extend({}, $modalProvider.options, modalOptions);
  1857. modalOptions.resolve = modalOptions.resolve || {};
  1858. //verify options
  1859. if (!modalOptions.template && !modalOptions.templateUrl) {
  1860. throw new Error('One of template or templateUrl options is required.');
  1861. }
  1862. var templateAndResolvePromise =
  1863. $q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve)));
  1864. templateAndResolvePromise.then(function resolveSuccess(tplAndVars) {
  1865. var modalScope = (modalOptions.scope || $rootScope).$new();
  1866. modalScope.$close = modalInstance.close;
  1867. modalScope.$dismiss = modalInstance.dismiss;
  1868. var ctrlInstance, ctrlLocals = {};
  1869. var resolveIter = 1;
  1870. //controllers
  1871. if (modalOptions.controller) {
  1872. ctrlLocals.$scope = modalScope;
  1873. ctrlLocals.$modalInstance = modalInstance;
  1874. angular.forEach(modalOptions.resolve, function (value, key) {
  1875. ctrlLocals[key] = tplAndVars[resolveIter++];
  1876. });
  1877. ctrlInstance = $controller(modalOptions.controller, ctrlLocals);
  1878. if (modalOptions.controllerAs) {
  1879. modalScope[modalOptions.controllerAs] = ctrlInstance;
  1880. }
  1881. }
  1882. $modalStack.open(modalInstance, {
  1883. scope: modalScope,
  1884. deferred: modalResultDeferred,
  1885. content: tplAndVars[0],
  1886. backdrop: modalOptions.backdrop,
  1887. keyboard: modalOptions.keyboard,
  1888. backdropClass: modalOptions.backdropClass,
  1889. windowClass: modalOptions.windowClass,
  1890. windowTemplateUrl: modalOptions.windowTemplateUrl,
  1891. size: modalOptions.size
  1892. });
  1893. }, function resolveError(reason) {
  1894. modalResultDeferred.reject(reason);
  1895. });
  1896. templateAndResolvePromise.then(function () {
  1897. modalOpenedDeferred.resolve(true);
  1898. }, function () {
  1899. modalOpenedDeferred.reject(false);
  1900. });
  1901. return modalInstance;
  1902. };
  1903. return $modal;
  1904. }]
  1905. };
  1906. return $modalProvider;
  1907. });
  1908. angular.module('ui.bootstrap.pagination', [])
  1909. .controller('PaginationController', ['$scope', '$attrs', '$parse', function ($scope, $attrs, $parse) {
  1910. var self = this,
  1911. ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl
  1912. setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop;
  1913. this.init = function(ngModelCtrl_, config) {
  1914. ngModelCtrl = ngModelCtrl_;
  1915. this.config = config;
  1916. ngModelCtrl.$render = function() {
  1917. self.render();
  1918. };
  1919. if ($attrs.itemsPerPage) {
  1920. $scope.$parent.$watch($parse($attrs.itemsPerPage), function(value) {
  1921. self.itemsPerPage = parseInt(value, 10);
  1922. $scope.totalPages = self.calculateTotalPages();
  1923. });
  1924. } else {
  1925. this.itemsPerPage = config.itemsPerPage;
  1926. }
  1927. };
  1928. this.calculateTotalPages = function() {
  1929. var totalPages = this.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / this.itemsPerPage);
  1930. return Math.max(totalPages || 0, 1);
  1931. };
  1932. this.render = function() {
  1933. $scope.page = parseInt(ngModelCtrl.$viewValue, 10) || 1;
  1934. };
  1935. $scope.selectPage = function(page) {
  1936. if ( $scope.page !== page && page > 0 && page <= $scope.totalPages) {
  1937. ngModelCtrl.$setViewValue(page);
  1938. ngModelCtrl.$render();
  1939. }
  1940. };
  1941. $scope.getText = function( key ) {
  1942. return $scope[key + 'Text'] || self.config[key + 'Text'];
  1943. };
  1944. $scope.noPrevious = function() {
  1945. return $scope.page === 1;
  1946. };
  1947. $scope.noNext = function() {
  1948. return $scope.page === $scope.totalPages;
  1949. };
  1950. $scope.$watch('totalItems', function() {
  1951. $scope.totalPages = self.calculateTotalPages();
  1952. });
  1953. $scope.$watch('totalPages', function(value) {
  1954. setNumPages($scope.$parent, value); // Readonly variable
  1955. if ( $scope.page > value ) {
  1956. $scope.selectPage(value);
  1957. } else {
  1958. ngModelCtrl.$render();
  1959. }
  1960. });
  1961. }])
  1962. .constant('paginationConfig', {
  1963. itemsPerPage: 10,
  1964. boundaryLinks: false,
  1965. directionLinks: true,
  1966. firstText: 'First',
  1967. previousText: 'Previous',
  1968. nextText: 'Next',
  1969. lastText: 'Last',
  1970. rotate: true
  1971. })
  1972. .directive('pagination', ['$parse', 'paginationConfig', function($parse, paginationConfig) {
  1973. return {
  1974. restrict: 'EA',
  1975. scope: {
  1976. totalItems: '=',
  1977. firstText: '@',
  1978. previousText: '@',
  1979. nextText: '@',
  1980. lastText: '@'
  1981. },
  1982. require: ['pagination', '?ngModel'],
  1983. controller: 'PaginationController',
  1984. templateUrl: 'template/pagination/pagination.html',
  1985. replace: true,
  1986. link: function(scope, element, attrs, ctrls) {
  1987. var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];
  1988. if (!ngModelCtrl) {
  1989. return; // do nothing if no ng-model
  1990. }
  1991. // Setup configuration parameters
  1992. var maxSize = angular.isDefined(attrs.maxSize) ? scope.$parent.$eval(attrs.maxSize) : paginationConfig.maxSize,
  1993. rotate = angular.isDefined(attrs.rotate) ? scope.$parent.$eval(attrs.rotate) : paginationConfig.rotate;
  1994. scope.boundaryLinks = angular.isDefined(attrs.boundaryLinks) ? scope.$parent.$eval(attrs.boundaryLinks) : paginationConfig.boundaryLinks;
  1995. scope.directionLinks = angular.isDefined(attrs.directionLinks) ? scope.$parent.$eval(attrs.directionLinks) : paginationConfig.directionLinks;
  1996. paginationCtrl.init(ngModelCtrl, paginationConfig);
  1997. if (attrs.maxSize) {
  1998. scope.$parent.$watch($parse(attrs.maxSize), function(value) {
  1999. maxSize = parseInt(value, 10);
  2000. paginationCtrl.render();
  2001. });
  2002. }
  2003. // Create page object used in template
  2004. function makePage(number, text, isActive) {
  2005. return {
  2006. number: number,
  2007. text: text,
  2008. active: isActive
  2009. };
  2010. }
  2011. function getPages(currentPage, totalPages) {
  2012. var pages = [];
  2013. // Default page limits
  2014. var startPage = 1, endPage = totalPages;
  2015. var isMaxSized = ( angular.isDefined(maxSize) && maxSize < totalPages );
  2016. // recompute if maxSize
  2017. if ( isMaxSized ) {
  2018. if ( rotate ) {
  2019. // Current page is displayed in the middle of the visible ones
  2020. startPage = Math.max(currentPage - Math.floor(maxSize/2), 1);
  2021. endPage = startPage + maxSize - 1;
  2022. // Adjust if limit is exceeded
  2023. if (endPage > totalPages) {
  2024. endPage = totalPages;
  2025. startPage = endPage - maxSize + 1;
  2026. }
  2027. } else {
  2028. // Visible pages are paginated with maxSize
  2029. startPage = ((Math.ceil(currentPage / maxSize) - 1) * maxSize) + 1;
  2030. // Adjust last page if limit is exceeded
  2031. endPage = Math.min(startPage + maxSize - 1, totalPages);
  2032. }
  2033. }
  2034. // Add page number links
  2035. for (var number = startPage; number <= endPage; number++) {
  2036. var page = makePage(number, number, number === currentPage);
  2037. pages.push(page);
  2038. }
  2039. // Add links to move between page sets
  2040. if ( isMaxSized && ! rotate ) {
  2041. if ( startPage > 1 ) {
  2042. var previousPageSet = makePage(startPage - 1, '...', false);
  2043. pages.unshift(previousPageSet);
  2044. }
  2045. if ( endPage < totalPages ) {
  2046. var nextPageSet = makePage(endPage + 1, '...', false);
  2047. pages.push(nextPageSet);
  2048. }
  2049. }
  2050. return pages;
  2051. }
  2052. var originalRender = paginationCtrl.render;
  2053. paginationCtrl.render = function() {
  2054. originalRender();
  2055. if (scope.page > 0 && scope.page <= scope.totalPages) {
  2056. scope.pages = getPages(scope.page, scope.totalPages);
  2057. }
  2058. };
  2059. }
  2060. };
  2061. }])
  2062. .constant('pagerConfig', {
  2063. itemsPerPage: 10,
  2064. previousText: '« Previous',
  2065. nextText: 'Next »',
  2066. align: true
  2067. })
  2068. .directive('pager', ['pagerConfig', function(pagerConfig) {
  2069. return {
  2070. restrict: 'EA',
  2071. scope: {
  2072. totalItems: '=',
  2073. previousText: '@',
  2074. nextText: '@'
  2075. },
  2076. require: ['pager', '?ngModel'],
  2077. controller: 'PaginationController',
  2078. templateUrl: 'template/pagination/pager.html',
  2079. replace: true,
  2080. link: function(scope, element, attrs, ctrls) {
  2081. var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];
  2082. if (!ngModelCtrl) {
  2083. return; // do nothing if no ng-model
  2084. }
  2085. scope.align = angular.isDefined(attrs.align) ? scope.$parent.$eval(attrs.align) : pagerConfig.align;
  2086. paginationCtrl.init(ngModelCtrl, pagerConfig);
  2087. }
  2088. };
  2089. }]);
  2090. /**
  2091. * The following features are still outstanding: animation as a
  2092. * function, placement as a function, inside, support for more triggers than
  2093. * just mouse enter/leave, html tooltips, and selector delegation.
  2094. */
  2095. angular.module( 'ui.bootstrap.tooltip', [ 'ui.bootstrap.position', 'ui.bootstrap.bindHtml' ] )
  2096. /**
  2097. * The $tooltip service creates tooltip- and popover-like directives as well as
  2098. * houses global options for them.
  2099. */
  2100. .provider( '$tooltip', function () {
  2101. // The default options tooltip and popover.
  2102. var defaultOptions = {
  2103. placement: 'top',
  2104. animation: true,
  2105. popupDelay: 0
  2106. };
  2107. // Default hide triggers for each show trigger
  2108. var triggerMap = {
  2109. 'mouseenter': 'mouseleave',
  2110. 'click': 'click',
  2111. 'focus': 'blur'
  2112. };
  2113. // The options specified to the provider globally.
  2114. var globalOptions = {};
  2115. /**
  2116. * `options({})` allows global configuration of all tooltips in the
  2117. * application.
  2118. *
  2119. * var app = angular.module( 'App', ['ui.bootstrap.tooltip'], function( $tooltipProvider ) {
  2120. * // place tooltips left instead of top by default
  2121. * $tooltipProvider.options( { placement: 'left' } );
  2122. * });
  2123. */
  2124. this.options = function( value ) {
  2125. angular.extend( globalOptions, value );
  2126. };
  2127. /**
  2128. * This allows you to extend the set of trigger mappings available. E.g.:
  2129. *
  2130. * $tooltipProvider.setTriggers( 'openTrigger': 'closeTrigger' );
  2131. */
  2132. this.setTriggers = function setTriggers ( triggers ) {
  2133. angular.extend( triggerMap, triggers );
  2134. };
  2135. /**
  2136. * This is a helper function for translating camel-case to snake-case.
  2137. */
  2138. function snake_case(name){
  2139. var regexp = /[A-Z]/g;
  2140. var separator = '-';
  2141. return name.replace(regexp, function(letter, pos) {
  2142. return (pos ? separator : '') + letter.toLowerCase();
  2143. });
  2144. }
  2145. /**
  2146. * Returns the actual instance of the $tooltip service.
  2147. * TODO support multiple triggers
  2148. */
  2149. this.$get = [ '$window', '$compile', '$timeout', '$document', '$position', '$interpolate', function ( $window, $compile, $timeout, $document, $position, $interpolate ) {
  2150. return function $tooltip ( type, prefix, defaultTriggerShow ) {
  2151. var options = angular.extend( {}, defaultOptions, globalOptions );
  2152. /**
  2153. * Returns an object of show and hide triggers.
  2154. *
  2155. * If a trigger is supplied,
  2156. * it is used to show the tooltip; otherwise, it will use the `trigger`
  2157. * option passed to the `$tooltipProvider.options` method; else it will
  2158. * default to the trigger supplied to this directive factory.
  2159. *
  2160. * The hide trigger is based on the show trigger. If the `trigger` option
  2161. * was passed to the `$tooltipProvider.options` method, it will use the
  2162. * mapped trigger from `triggerMap` or the passed trigger if the map is
  2163. * undefined; otherwise, it uses the `triggerMap` value of the show
  2164. * trigger; else it will just use the show trigger.
  2165. */
  2166. function getTriggers ( trigger ) {
  2167. var show = trigger || options.trigger || defaultTriggerShow;
  2168. var hide = triggerMap[show] || show;
  2169. return {
  2170. show: show,
  2171. hide: hide
  2172. };
  2173. }
  2174. var directiveName = snake_case( type );
  2175. var startSym = $interpolate.startSymbol();
  2176. var endSym = $interpolate.endSymbol();
  2177. var template =
  2178. '<div '+ directiveName +'-popup '+
  2179. 'title="'+startSym+'title'+endSym+'" '+
  2180. 'content="'+startSym+'content'+endSym+'" '+
  2181. 'placement="'+startSym+'placement'+endSym+'" '+
  2182. 'animation="animation" '+
  2183. 'is-open="isOpen"'+
  2184. '>'+
  2185. '</div>';
  2186. return {
  2187. restrict: 'EA',
  2188. compile: function (tElem, tAttrs) {
  2189. var tooltipLinker = $compile( template );
  2190. return function link ( scope, element, attrs ) {
  2191. var tooltip;
  2192. var tooltipLinkedScope;
  2193. var transitionTimeout;
  2194. var popupTimeout;
  2195. var appendToBody = angular.isDefined( options.appendToBody ) ? options.appendToBody : false;
  2196. var triggers = getTriggers( undefined );
  2197. var hasEnableExp = angular.isDefined(attrs[prefix+'Enable']);
  2198. var ttScope = scope.$new(true);
  2199. var positionTooltip = function () {
  2200. var ttPosition = $position.positionElements(element, tooltip, ttScope.placement, appendToBody);
  2201. ttPosition.top += 'px';
  2202. ttPosition.left += 'px';
  2203. // Now set the calculated positioning.
  2204. tooltip.css( ttPosition );
  2205. };
  2206. // By default, the tooltip is not open.
  2207. // TODO add ability to start tooltip opened
  2208. ttScope.isOpen = false;
  2209. function toggleTooltipBind () {
  2210. if ( ! ttScope.isOpen ) {
  2211. showTooltipBind();
  2212. } else {
  2213. hideTooltipBind();
  2214. }
  2215. }
  2216. // Show the tooltip with delay if specified, otherwise show it immediately
  2217. function showTooltipBind() {
  2218. if(hasEnableExp && !scope.$eval(attrs[prefix+'Enable'])) {
  2219. return;
  2220. }
  2221. prepareTooltip();
  2222. if ( ttScope.popupDelay ) {
  2223. // Do nothing if the tooltip was already scheduled to pop-up.
  2224. // This happens if show is triggered multiple times before any hide is triggered.
  2225. if (!popupTimeout) {
  2226. popupTimeout = $timeout( show, ttScope.popupDelay, false );
  2227. popupTimeout.then(function(reposition){reposition();});
  2228. }
  2229. } else {
  2230. show()();
  2231. }
  2232. }
  2233. function hideTooltipBind () {
  2234. scope.$apply(function () {
  2235. hide();
  2236. });
  2237. }
  2238. // Show the tooltip popup element.
  2239. function show() {
  2240. popupTimeout = null;
  2241. // If there is a pending remove transition, we must cancel it, lest the
  2242. // tooltip be mysteriously removed.
  2243. if ( transitionTimeout ) {
  2244. $timeout.cancel( transitionTimeout );
  2245. transitionTimeout = null;
  2246. }
  2247. // Don't show empty tooltips.
  2248. if ( ! ttScope.content ) {
  2249. return angular.noop;
  2250. }
  2251. createTooltip();
  2252. // Set the initial positioning.
  2253. tooltip.css({ top: 0, left: 0, display: 'block' });
  2254. ttScope.$digest();
  2255. positionTooltip();
  2256. // And show the tooltip.
  2257. ttScope.isOpen = true;
  2258. ttScope.$digest(); // digest required as $apply is not called
  2259. // Return positioning function as promise callback for correct
  2260. // positioning after draw.
  2261. return positionTooltip;
  2262. }
  2263. // Hide the tooltip popup element.
  2264. function hide() {
  2265. // First things first: we don't show it anymore.
  2266. ttScope.isOpen = false;
  2267. //if tooltip is going to be shown after delay, we must cancel this
  2268. $timeout.cancel( popupTimeout );
  2269. popupTimeout = null;
  2270. // And now we remove it from the DOM. However, if we have animation, we
  2271. // need to wait for it to expire beforehand.
  2272. // FIXME: this is a placeholder for a port of the transitions library.
  2273. if ( ttScope.animation ) {
  2274. if (!transitionTimeout) {
  2275. transitionTimeout = $timeout(removeTooltip, 500);
  2276. }
  2277. } else {
  2278. removeTooltip();
  2279. }
  2280. }
  2281. function createTooltip() {
  2282. // There can only be one tooltip element per directive shown at once.
  2283. if (tooltip) {
  2284. removeTooltip();
  2285. }
  2286. tooltipLinkedScope = ttScope.$new();
  2287. tooltip = tooltipLinker(tooltipLinkedScope, function (tooltip) {
  2288. if ( appendToBody ) {
  2289. $document.find( 'body' ).append( tooltip );
  2290. } else {
  2291. element.after( tooltip );
  2292. }
  2293. });
  2294. }
  2295. function removeTooltip() {
  2296. transitionTimeout = null;
  2297. if (tooltip) {
  2298. tooltip.remove();
  2299. tooltip = null;
  2300. }
  2301. if (tooltipLinkedScope) {
  2302. tooltipLinkedScope.$destroy();
  2303. tooltipLinkedScope = null;
  2304. }
  2305. }
  2306. function prepareTooltip() {
  2307. prepPlacement();
  2308. prepPopupDelay();
  2309. }
  2310. /**
  2311. * Observe the relevant attributes.
  2312. */
  2313. attrs.$observe( type, function ( val ) {
  2314. ttScope.content = val;
  2315. if (!val && ttScope.isOpen ) {
  2316. hide();
  2317. }
  2318. });
  2319. attrs.$observe( prefix+'Title', function ( val ) {
  2320. ttScope.title = val;
  2321. });
  2322. function prepPlacement() {
  2323. var val = attrs[ prefix + 'Placement' ];
  2324. ttScope.placement = angular.isDefined( val ) ? val : options.placement;
  2325. }
  2326. function prepPopupDelay() {
  2327. var val = attrs[ prefix + 'PopupDelay' ];
  2328. var delay = parseInt( val, 10 );
  2329. ttScope.popupDelay = ! isNaN(delay) ? delay : options.popupDelay;
  2330. }
  2331. var unregisterTriggers = function () {
  2332. element.unbind(triggers.show, showTooltipBind);
  2333. element.unbind(triggers.hide, hideTooltipBind);
  2334. };
  2335. function prepTriggers() {
  2336. var val = attrs[ prefix + 'Trigger' ];
  2337. unregisterTriggers();
  2338. triggers = getTriggers( val );
  2339. if ( triggers.show === triggers.hide ) {
  2340. element.bind( triggers.show, toggleTooltipBind );
  2341. } else {
  2342. element.bind( triggers.show, showTooltipBind );
  2343. element.bind( triggers.hide, hideTooltipBind );
  2344. }
  2345. }
  2346. prepTriggers();
  2347. var animation = scope.$eval(attrs[prefix + 'Animation']);
  2348. ttScope.animation = angular.isDefined(animation) ? !!animation : options.animation;
  2349. var appendToBodyVal = scope.$eval(attrs[prefix + 'AppendToBody']);
  2350. appendToBody = angular.isDefined(appendToBodyVal) ? appendToBodyVal : appendToBody;
  2351. // if a tooltip is attached to <body> we need to remove it on
  2352. // location change as its parent scope will probably not be destroyed
  2353. // by the change.
  2354. if ( appendToBody ) {
  2355. scope.$on('$locationChangeSuccess', function closeTooltipOnLocationChangeSuccess () {
  2356. if ( ttScope.isOpen ) {
  2357. hide();
  2358. }
  2359. });
  2360. }
  2361. // Make sure tooltip is destroyed and removed.
  2362. scope.$on('$destroy', function onDestroyTooltip() {
  2363. $timeout.cancel( transitionTimeout );
  2364. $timeout.cancel( popupTimeout );
  2365. unregisterTriggers();
  2366. removeTooltip();
  2367. ttScope = null;
  2368. });
  2369. };
  2370. }
  2371. };
  2372. };
  2373. }];
  2374. })
  2375. .directive( 'tooltipPopup', function () {
  2376. return {
  2377. restrict: 'EA',
  2378. replace: true,
  2379. scope: { content: '@', placement: '@', animation: '&', isOpen: '&' },
  2380. templateUrl: 'template/tooltip/tooltip-popup.html'
  2381. };
  2382. })
  2383. .directive( 'tooltip', [ '$tooltip', function ( $tooltip ) {
  2384. return $tooltip( 'tooltip', 'tooltip', 'mouseenter' );
  2385. }])
  2386. .directive( 'tooltipHtmlUnsafePopup', function () {
  2387. return {
  2388. restrict: 'EA',
  2389. replace: true,
  2390. scope: { content: '@', placement: '@', animation: '&', isOpen: '&' },
  2391. templateUrl: 'template/tooltip/tooltip-html-unsafe-popup.html'
  2392. };
  2393. })
  2394. .directive( 'tooltipHtmlUnsafe', [ '$tooltip', function ( $tooltip ) {
  2395. return $tooltip( 'tooltipHtmlUnsafe', 'tooltip', 'mouseenter' );
  2396. }]);
  2397. /**
  2398. * The following features are still outstanding: popup delay, animation as a
  2399. * function, placement as a function, inside, support for more triggers than
  2400. * just mouse enter/leave, html popovers, and selector delegatation.
  2401. */
  2402. angular.module( 'ui.bootstrap.popover', [ 'ui.bootstrap.tooltip' ] )
  2403. .directive( 'popoverPopup', function () {
  2404. return {
  2405. restrict: 'EA',
  2406. replace: true,
  2407. scope: { title: '@', content: '@', placement: '@', animation: '&', isOpen: '&' },
  2408. templateUrl: 'template/popover/popover.html'
  2409. };
  2410. })
  2411. .directive( 'popover', [ '$tooltip', function ( $tooltip ) {
  2412. return $tooltip( 'popover', 'popover', 'click' );
  2413. }]);
  2414. angular.module('ui.bootstrap.progressbar', [])
  2415. .constant('progressConfig', {
  2416. animate: true,
  2417. max: 100
  2418. })
  2419. .controller('ProgressController', ['$scope', '$attrs', 'progressConfig', function($scope, $attrs, progressConfig) {
  2420. var self = this,
  2421. animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate;
  2422. this.bars = [];
  2423. $scope.max = angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : progressConfig.max;
  2424. this.addBar = function(bar, element) {
  2425. if ( !animate ) {
  2426. element.css({'transition': 'none'});
  2427. }
  2428. this.bars.push(bar);
  2429. bar.$watch('value', function( value ) {
  2430. bar.percent = +(100 * value / $scope.max).toFixed(2);
  2431. });
  2432. bar.$on('$destroy', function() {
  2433. element = null;
  2434. self.removeBar(bar);
  2435. });
  2436. };
  2437. this.removeBar = function(bar) {
  2438. this.bars.splice(this.bars.indexOf(bar), 1);
  2439. };
  2440. }])
  2441. .directive('progress', function() {
  2442. return {
  2443. restrict: 'EA',
  2444. replace: true,
  2445. transclude: true,
  2446. controller: 'ProgressController',
  2447. require: 'progress',
  2448. scope: {},
  2449. templateUrl: 'template/progressbar/progress.html'
  2450. };
  2451. })
  2452. .directive('bar', function() {
  2453. return {
  2454. restrict: 'EA',
  2455. replace: true,
  2456. transclude: true,
  2457. require: '^progress',
  2458. scope: {
  2459. value: '=',
  2460. type: '@'
  2461. },
  2462. templateUrl: 'template/progressbar/bar.html',
  2463. link: function(scope, element, attrs, progressCtrl) {
  2464. progressCtrl.addBar(scope, element);
  2465. }
  2466. };
  2467. })
  2468. .directive('progressbar', function() {
  2469. return {
  2470. restrict: 'EA',
  2471. replace: true,
  2472. transclude: true,
  2473. controller: 'ProgressController',
  2474. scope: {
  2475. value: '=',
  2476. type: '@'
  2477. },
  2478. templateUrl: 'template/progressbar/progressbar.html',
  2479. link: function(scope, element, attrs, progressCtrl) {
  2480. progressCtrl.addBar(scope, angular.element(element.children()[0]));
  2481. }
  2482. };
  2483. });
  2484. angular.module('ui.bootstrap.rating', [])
  2485. .constant('ratingConfig', {
  2486. max: 5,
  2487. stateOn: null,
  2488. stateOff: null
  2489. })
  2490. .controller('RatingController', ['$scope', '$attrs', 'ratingConfig', function($scope, $attrs, ratingConfig) {
  2491. var ngModelCtrl = { $setViewValue: angular.noop };
  2492. this.init = function(ngModelCtrl_) {
  2493. ngModelCtrl = ngModelCtrl_;
  2494. ngModelCtrl.$render = this.render;
  2495. this.stateOn = angular.isDefined($attrs.stateOn) ? $scope.$parent.$eval($attrs.stateOn) : ratingConfig.stateOn;
  2496. this.stateOff = angular.isDefined($attrs.stateOff) ? $scope.$parent.$eval($attrs.stateOff) : ratingConfig.stateOff;
  2497. var ratingStates = angular.isDefined($attrs.ratingStates) ? $scope.$parent.$eval($attrs.ratingStates) :
  2498. new Array( angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : ratingConfig.max );
  2499. $scope.range = this.buildTemplateObjects(ratingStates);
  2500. };
  2501. this.buildTemplateObjects = function(states) {
  2502. for (var i = 0, n = states.length; i < n; i++) {
  2503. states[i] = angular.extend({ index: i }, { stateOn: this.stateOn, stateOff: this.stateOff }, states[i]);
  2504. }
  2505. return states;
  2506. };
  2507. $scope.rate = function(value) {
  2508. if ( !$scope.readonly && value >= 0 && value <= $scope.range.length ) {
  2509. ngModelCtrl.$setViewValue(value);
  2510. ngModelCtrl.$render();
  2511. }
  2512. };
  2513. $scope.enter = function(value) {
  2514. if ( !$scope.readonly ) {
  2515. $scope.value = value;
  2516. }
  2517. $scope.onHover({value: value});
  2518. };
  2519. $scope.reset = function() {
  2520. $scope.value = ngModelCtrl.$viewValue;
  2521. $scope.onLeave();
  2522. };
  2523. $scope.onKeydown = function(evt) {
  2524. if (/(37|38|39|40)/.test(evt.which)) {
  2525. evt.preventDefault();
  2526. evt.stopPropagation();
  2527. $scope.rate( $scope.value + (evt.which === 38 || evt.which === 39 ? 1 : -1) );
  2528. }
  2529. };
  2530. this.render = function() {
  2531. $scope.value = ngModelCtrl.$viewValue;
  2532. };
  2533. }])
  2534. .directive('rating', function() {
  2535. return {
  2536. restrict: 'EA',
  2537. require: ['rating', 'ngModel'],
  2538. scope: {
  2539. readonly: '=?',
  2540. onHover: '&',
  2541. onLeave: '&'
  2542. },
  2543. controller: 'RatingController',
  2544. templateUrl: 'template/rating/rating.html',
  2545. replace: true,
  2546. link: function(scope, element, attrs, ctrls) {
  2547. var ratingCtrl = ctrls[0], ngModelCtrl = ctrls[1];
  2548. if ( ngModelCtrl ) {
  2549. ratingCtrl.init( ngModelCtrl );
  2550. }
  2551. }
  2552. };
  2553. });
  2554. /**
  2555. * @ngdoc overview
  2556. * @name ui.bootstrap.tabs
  2557. *
  2558. * @description
  2559. * AngularJS version of the tabs directive.
  2560. */
  2561. angular.module('ui.bootstrap.tabs', [])
  2562. .controller('TabsetController', ['$scope', function TabsetCtrl($scope) {
  2563. var ctrl = this,
  2564. tabs = ctrl.tabs = $scope.tabs = [];
  2565. ctrl.select = function(selectedTab) {
  2566. angular.forEach(tabs, function(tab) {
  2567. if (tab.active && tab !== selectedTab) {
  2568. tab.active = false;
  2569. tab.onDeselect();
  2570. }
  2571. });
  2572. selectedTab.active = true;
  2573. selectedTab.onSelect();
  2574. };
  2575. ctrl.addTab = function addTab(tab) {
  2576. tabs.push(tab);
  2577. // we can't run the select function on the first tab
  2578. // since that would select it twice
  2579. if (tabs.length === 1) {
  2580. tab.active = true;
  2581. } else if (tab.active) {
  2582. ctrl.select(tab);
  2583. }
  2584. };
  2585. ctrl.removeTab = function removeTab(tab) {
  2586. var index = tabs.indexOf(tab);
  2587. //Select a new tab if the tab to be removed is selected and not destroyed
  2588. if (tab.active && tabs.length > 1 && !destroyed) {
  2589. //If this is the last tab, select the previous tab. else, the next tab.
  2590. var newActiveIndex = index == tabs.length - 1 ? index - 1 : index + 1;
  2591. ctrl.select(tabs[newActiveIndex]);
  2592. }
  2593. tabs.splice(index, 1);
  2594. };
  2595. var destroyed;
  2596. $scope.$on('$destroy', function() {
  2597. destroyed = true;
  2598. });
  2599. }])
  2600. /**
  2601. * @ngdoc directive
  2602. * @name ui.bootstrap.tabs.directive:tabset
  2603. * @restrict EA
  2604. *
  2605. * @description
  2606. * Tabset is the outer container for the tabs directive
  2607. *
  2608. * @param {boolean=} vertical Whether or not to use vertical styling for the tabs.
  2609. * @param {boolean=} justified Whether or not to use justified styling for the tabs.
  2610. *
  2611. * @example
  2612. <example module="ui.bootstrap">
  2613. <file name="index.html">
  2614. <tabset>
  2615. <tab heading="Tab 1"><b>First</b> Content!</tab>
  2616. <tab heading="Tab 2"><i>Second</i> Content!</tab>
  2617. </tabset>
  2618. <hr />
  2619. <tabset vertical="true">
  2620. <tab heading="Vertical Tab 1"><b>First</b> Vertical Content!</tab>
  2621. <tab heading="Vertical Tab 2"><i>Second</i> Vertical Content!</tab>
  2622. </tabset>
  2623. <tabset justified="true">
  2624. <tab heading="Justified Tab 1"><b>First</b> Justified Content!</tab>
  2625. <tab heading="Justified Tab 2"><i>Second</i> Justified Content!</tab>
  2626. </tabset>
  2627. </file>
  2628. </example>
  2629. */
  2630. .directive('tabset', function() {
  2631. return {
  2632. restrict: 'EA',
  2633. transclude: true,
  2634. replace: true,
  2635. scope: {
  2636. type: '@'
  2637. },
  2638. controller: 'TabsetController',
  2639. templateUrl: 'template/tabs/tabset.html',
  2640. link: function(scope, element, attrs) {
  2641. scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false;
  2642. scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false;
  2643. }
  2644. };
  2645. })
  2646. /**
  2647. * @ngdoc directive
  2648. * @name ui.bootstrap.tabs.directive:tab
  2649. * @restrict EA
  2650. *
  2651. * @param {string=} heading The visible heading, or title, of the tab. Set HTML headings with {@link ui.bootstrap.tabs.directive:tabHeading tabHeading}.
  2652. * @param {string=} select An expression to evaluate when the tab is selected.
  2653. * @param {boolean=} active A binding, telling whether or not this tab is selected.
  2654. * @param {boolean=} disabled A binding, telling whether or not this tab is disabled.
  2655. *
  2656. * @description
  2657. * Creates a tab with a heading and content. Must be placed within a {@link ui.bootstrap.tabs.directive:tabset tabset}.
  2658. *
  2659. * @example
  2660. <example module="ui.bootstrap">
  2661. <file name="index.html">
  2662. <div ng-controller="TabsDemoCtrl">
  2663. <button class="btn btn-small" ng-click="items[0].active = true">
  2664. Select item 1, using active binding
  2665. </button>
  2666. <button class="btn btn-small" ng-click="items[1].disabled = !items[1].disabled">
  2667. Enable/disable item 2, using disabled binding
  2668. </button>
  2669. <br />
  2670. <tabset>
  2671. <tab heading="Tab 1">First Tab</tab>
  2672. <tab select="alertMe()">
  2673. <tab-heading><i class="icon-bell"></i> Alert me!</tab-heading>
  2674. Second Tab, with alert callback and html heading!
  2675. </tab>
  2676. <tab ng-repeat="item in items"
  2677. heading="{{item.title}}"
  2678. disabled="item.disabled"
  2679. active="item.active">
  2680. {{item.content}}
  2681. </tab>
  2682. </tabset>
  2683. </div>
  2684. </file>
  2685. <file name="script.js">
  2686. function TabsDemoCtrl($scope) {
  2687. $scope.items = [
  2688. { title:"Dynamic Title 1", content:"Dynamic Item 0" },
  2689. { title:"Dynamic Title 2", content:"Dynamic Item 1", disabled: true }
  2690. ];
  2691. $scope.alertMe = function() {
  2692. setTimeout(function() {
  2693. alert("You've selected the alert tab!");
  2694. });
  2695. };
  2696. };
  2697. </file>
  2698. </example>
  2699. */
  2700. /**
  2701. * @ngdoc directive
  2702. * @name ui.bootstrap.tabs.directive:tabHeading
  2703. * @restrict EA
  2704. *
  2705. * @description
  2706. * Creates an HTML heading for a {@link ui.bootstrap.tabs.directive:tab tab}. Must be placed as a child of a tab element.
  2707. *
  2708. * @example
  2709. <example module="ui.bootstrap">
  2710. <file name="index.html">
  2711. <tabset>
  2712. <tab>
  2713. <tab-heading><b>HTML</b> in my titles?!</tab-heading>
  2714. And some content, too!
  2715. </tab>
  2716. <tab>
  2717. <tab-heading><i class="icon-heart"></i> Icon heading?!?</tab-heading>
  2718. That's right.
  2719. </tab>
  2720. </tabset>
  2721. </file>
  2722. </example>
  2723. */
  2724. .directive('tab', ['$parse', function($parse) {
  2725. return {
  2726. require: '^tabset',
  2727. restrict: 'EA',
  2728. replace: true,
  2729. templateUrl: 'template/tabs/tab.html',
  2730. transclude: true,
  2731. scope: {
  2732. active: '=?',
  2733. heading: '@',
  2734. onSelect: '&select', //This callback is called in contentHeadingTransclude
  2735. //once it inserts the tab's content into the dom
  2736. onDeselect: '&deselect'
  2737. },
  2738. controller: function() {
  2739. //Empty controller so other directives can require being 'under' a tab
  2740. },
  2741. compile: function(elm, attrs, transclude) {
  2742. return function postLink(scope, elm, attrs, tabsetCtrl) {
  2743. scope.$watch('active', function(active) {
  2744. if (active) {
  2745. tabsetCtrl.select(scope);
  2746. }
  2747. });
  2748. scope.disabled = false;
  2749. if ( attrs.disabled ) {
  2750. scope.$parent.$watch($parse(attrs.disabled), function(value) {
  2751. scope.disabled = !! value;
  2752. });
  2753. }
  2754. scope.select = function() {
  2755. if ( !scope.disabled ) {
  2756. scope.active = true;
  2757. }
  2758. };
  2759. tabsetCtrl.addTab(scope);
  2760. scope.$on('$destroy', function() {
  2761. tabsetCtrl.removeTab(scope);
  2762. });
  2763. //We need to transclude later, once the content container is ready.
  2764. //when this link happens, we're inside a tab heading.
  2765. scope.$transcludeFn = transclude;
  2766. };
  2767. }
  2768. };
  2769. }])
  2770. .directive('tabHeadingTransclude', [function() {
  2771. return {
  2772. restrict: 'A',
  2773. require: '^tab',
  2774. link: function(scope, elm, attrs, tabCtrl) {
  2775. scope.$watch('headingElement', function updateHeadingElement(heading) {
  2776. if (heading) {
  2777. elm.html('');
  2778. elm.append(heading);
  2779. }
  2780. });
  2781. }
  2782. };
  2783. }])
  2784. .directive('tabContentTransclude', function() {
  2785. return {
  2786. restrict: 'A',
  2787. require: '^tabset',
  2788. link: function(scope, elm, attrs) {
  2789. var tab = scope.$eval(attrs.tabContentTransclude);
  2790. //Now our tab is ready to be transcluded: both the tab heading area
  2791. //and the tab content area are loaded. Transclude 'em both.
  2792. tab.$transcludeFn(tab.$parent, function(contents) {
  2793. angular.forEach(contents, function(node) {
  2794. if (isTabHeading(node)) {
  2795. //Let tabHeadingTransclude know.
  2796. tab.headingElement = node;
  2797. } else {
  2798. elm.append(node);
  2799. }
  2800. });
  2801. });
  2802. }
  2803. };
  2804. function isTabHeading(node) {
  2805. return node.tagName && (
  2806. node.hasAttribute('tab-heading') ||
  2807. node.hasAttribute('data-tab-heading') ||
  2808. node.tagName.toLowerCase() === 'tab-heading' ||
  2809. node.tagName.toLowerCase() === 'data-tab-heading'
  2810. );
  2811. }
  2812. })
  2813. ;
  2814. angular.module('ui.bootstrap.timepicker', [])
  2815. .constant('timepickerConfig', {
  2816. hourStep: 1,
  2817. minuteStep: 1,
  2818. showMeridian: true,
  2819. meridians: null,
  2820. readonlyInput: false,
  2821. mousewheel: true
  2822. })
  2823. .controller('TimepickerController', ['$scope', '$attrs', '$parse', '$log', '$locale', 'timepickerConfig', function($scope, $attrs, $parse, $log, $locale, timepickerConfig) {
  2824. var selected = new Date(),
  2825. ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl
  2826. meridians = angular.isDefined($attrs.meridians) ? $scope.$parent.$eval($attrs.meridians) : timepickerConfig.meridians || $locale.DATETIME_FORMATS.AMPMS;
  2827. this.init = function( ngModelCtrl_, inputs ) {
  2828. ngModelCtrl = ngModelCtrl_;
  2829. ngModelCtrl.$render = this.render;
  2830. var hoursInputEl = inputs.eq(0),
  2831. minutesInputEl = inputs.eq(1);
  2832. var mousewheel = angular.isDefined($attrs.mousewheel) ? $scope.$parent.$eval($attrs.mousewheel) : timepickerConfig.mousewheel;
  2833. if ( mousewheel ) {
  2834. this.setupMousewheelEvents( hoursInputEl, minutesInputEl );
  2835. }
  2836. $scope.readonlyInput = angular.isDefined($attrs.readonlyInput) ? $scope.$parent.$eval($attrs.readonlyInput) : timepickerConfig.readonlyInput;
  2837. this.setupInputEvents( hoursInputEl, minutesInputEl );
  2838. };
  2839. var hourStep = timepickerConfig.hourStep;
  2840. if ($attrs.hourStep) {
  2841. $scope.$parent.$watch($parse($attrs.hourStep), function(value) {
  2842. hourStep = parseInt(value, 10);
  2843. });
  2844. }
  2845. var minuteStep = timepickerConfig.minuteStep;
  2846. if ($attrs.minuteStep) {
  2847. $scope.$parent.$watch($parse($attrs.minuteStep), function(value) {
  2848. minuteStep = parseInt(value, 10);
  2849. });
  2850. }
  2851. // 12H / 24H mode
  2852. $scope.showMeridian = timepickerConfig.showMeridian;
  2853. if ($attrs.showMeridian) {
  2854. $scope.$parent.$watch($parse($attrs.showMeridian), function(value) {
  2855. $scope.showMeridian = !!value;
  2856. if ( ngModelCtrl.$error.time ) {
  2857. // Evaluate from template
  2858. var hours = getHoursFromTemplate(), minutes = getMinutesFromTemplate();
  2859. if (angular.isDefined( hours ) && angular.isDefined( minutes )) {
  2860. selected.setHours( hours );
  2861. refresh();
  2862. }
  2863. } else {
  2864. updateTemplate();
  2865. }
  2866. });
  2867. }
  2868. // Get $scope.hours in 24H mode if valid
  2869. function getHoursFromTemplate ( ) {
  2870. var hours = parseInt( $scope.hours, 10 );
  2871. var valid = ( $scope.showMeridian ) ? (hours > 0 && hours < 13) : (hours >= 0 && hours < 24);
  2872. if ( !valid ) {
  2873. return undefined;
  2874. }
  2875. if ( $scope.showMeridian ) {
  2876. if ( hours === 12 ) {
  2877. hours = 0;
  2878. }
  2879. if ( $scope.meridian === meridians[1] ) {
  2880. hours = hours + 12;
  2881. }
  2882. }
  2883. return hours;
  2884. }
  2885. function getMinutesFromTemplate() {
  2886. var minutes = parseInt($scope.minutes, 10);
  2887. return ( minutes >= 0 && minutes < 60 ) ? minutes : undefined;
  2888. }
  2889. function pad( value ) {
  2890. return ( angular.isDefined(value) && value.toString().length < 2 ) ? '0' + value : value;
  2891. }
  2892. // Respond on mousewheel spin
  2893. this.setupMousewheelEvents = function( hoursInputEl, minutesInputEl ) {
  2894. var isScrollingUp = function(e) {
  2895. if (e.originalEvent) {
  2896. e = e.originalEvent;
  2897. }
  2898. //pick correct delta variable depending on event
  2899. var delta = (e.wheelDelta) ? e.wheelDelta : -e.deltaY;
  2900. return (e.detail || delta > 0);
  2901. };
  2902. hoursInputEl.bind('mousewheel wheel', function(e) {
  2903. $scope.$apply( (isScrollingUp(e)) ? $scope.incrementHours() : $scope.decrementHours() );
  2904. e.preventDefault();
  2905. });
  2906. minutesInputEl.bind('mousewheel wheel', function(e) {
  2907. $scope.$apply( (isScrollingUp(e)) ? $scope.incrementMinutes() : $scope.decrementMinutes() );
  2908. e.preventDefault();
  2909. });
  2910. };
  2911. this.setupInputEvents = function( hoursInputEl, minutesInputEl ) {
  2912. if ( $scope.readonlyInput ) {
  2913. $scope.updateHours = angular.noop;
  2914. $scope.updateMinutes = angular.noop;
  2915. return;
  2916. }
  2917. var invalidate = function(invalidHours, invalidMinutes) {
  2918. ngModelCtrl.$setViewValue( null );
  2919. ngModelCtrl.$setValidity('time', false);
  2920. if (angular.isDefined(invalidHours)) {
  2921. $scope.invalidHours = invalidHours;
  2922. }
  2923. if (angular.isDefined(invalidMinutes)) {
  2924. $scope.invalidMinutes = invalidMinutes;
  2925. }
  2926. };
  2927. $scope.updateHours = function() {
  2928. var hours = getHoursFromTemplate();
  2929. if ( angular.isDefined(hours) ) {
  2930. selected.setHours( hours );
  2931. refresh( 'h' );
  2932. } else {
  2933. invalidate(true);
  2934. }
  2935. };
  2936. hoursInputEl.bind('blur', function(e) {
  2937. if ( !$scope.invalidHours && $scope.hours < 10) {
  2938. $scope.$apply( function() {
  2939. $scope.hours = pad( $scope.hours );
  2940. });
  2941. }
  2942. });
  2943. $scope.updateMinutes = function() {
  2944. var minutes = getMinutesFromTemplate();
  2945. if ( angular.isDefined(minutes) ) {
  2946. selected.setMinutes( minutes );
  2947. refresh( 'm' );
  2948. } else {
  2949. invalidate(undefined, true);
  2950. }
  2951. };
  2952. minutesInputEl.bind('blur', function(e) {
  2953. if ( !$scope.invalidMinutes && $scope.minutes < 10 ) {
  2954. $scope.$apply( function() {
  2955. $scope.minutes = pad( $scope.minutes );
  2956. });
  2957. }
  2958. });
  2959. };
  2960. this.render = function() {
  2961. var date = ngModelCtrl.$modelValue ? new Date( ngModelCtrl.$modelValue ) : null;
  2962. if ( isNaN(date) ) {
  2963. ngModelCtrl.$setValidity('time', false);
  2964. $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.');
  2965. } else {
  2966. if ( date ) {
  2967. selected = date;
  2968. }
  2969. makeValid();
  2970. updateTemplate();
  2971. }
  2972. };
  2973. // Call internally when we know that model is valid.
  2974. function refresh( keyboardChange ) {
  2975. makeValid();
  2976. ngModelCtrl.$setViewValue( new Date(selected) );
  2977. updateTemplate( keyboardChange );
  2978. }
  2979. function makeValid() {
  2980. ngModelCtrl.$setValidity('time', true);
  2981. $scope.invalidHours = false;
  2982. $scope.invalidMinutes = false;
  2983. }
  2984. function updateTemplate( keyboardChange ) {
  2985. var hours = selected.getHours(), minutes = selected.getMinutes();
  2986. if ( $scope.showMeridian ) {
  2987. hours = ( hours === 0 || hours === 12 ) ? 12 : hours % 12; // Convert 24 to 12 hour system
  2988. }
  2989. $scope.hours = keyboardChange === 'h' ? hours : pad(hours);
  2990. $scope.minutes = keyboardChange === 'm' ? minutes : pad(minutes);
  2991. $scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1];
  2992. }
  2993. function addMinutes( minutes ) {
  2994. var dt = new Date( selected.getTime() + minutes * 60000 );
  2995. selected.setHours( dt.getHours(), dt.getMinutes() );
  2996. refresh();
  2997. }
  2998. $scope.incrementHours = function() {
  2999. addMinutes( hourStep * 60 );
  3000. };
  3001. $scope.decrementHours = function() {
  3002. addMinutes( - hourStep * 60 );
  3003. };
  3004. $scope.incrementMinutes = function() {
  3005. addMinutes( minuteStep );
  3006. };
  3007. $scope.decrementMinutes = function() {
  3008. addMinutes( - minuteStep );
  3009. };
  3010. $scope.toggleMeridian = function() {
  3011. addMinutes( 12 * 60 * (( selected.getHours() < 12 ) ? 1 : -1) );
  3012. };
  3013. }])
  3014. .directive('timepicker', function () {
  3015. return {
  3016. restrict: 'EA',
  3017. require: ['timepicker', '?^ngModel'],
  3018. controller:'TimepickerController',
  3019. replace: true,
  3020. scope: {},
  3021. templateUrl: 'template/timepicker/timepicker.html',
  3022. link: function(scope, element, attrs, ctrls) {
  3023. var timepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];
  3024. if ( ngModelCtrl ) {
  3025. timepickerCtrl.init( ngModelCtrl, element.find('input') );
  3026. }
  3027. }
  3028. };
  3029. });
  3030. angular.module('ui.bootstrap.typeahead', ['ui.bootstrap.position', 'ui.bootstrap.bindHtml'])
  3031. /**
  3032. * A helper service that can parse typeahead's syntax (string provided by users)
  3033. * Extracted to a separate service for ease of unit testing
  3034. */
  3035. .factory('typeaheadParser', ['$parse', function ($parse) {
  3036. // 00000111000000000000022200000000000000003333333333333330000000000044000
  3037. var TYPEAHEAD_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+([\s\S]+?)$/;
  3038. return {
  3039. parse:function (input) {
  3040. var match = input.match(TYPEAHEAD_REGEXP);
  3041. if (!match) {
  3042. throw new Error(
  3043. 'Expected typeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_"' +
  3044. ' but got "' + input + '".');
  3045. }
  3046. return {
  3047. itemName:match[3],
  3048. source:$parse(match[4]),
  3049. viewMapper:$parse(match[2] || match[1]),
  3050. modelMapper:$parse(match[1])
  3051. };
  3052. }
  3053. };
  3054. }])
  3055. .directive('typeahead', ['$compile', '$parse', '$q', '$timeout', '$document', '$position', 'typeaheadParser',
  3056. function ($compile, $parse, $q, $timeout, $document, $position, typeaheadParser) {
  3057. var HOT_KEYS = [9, 13, 27, 38, 40];
  3058. return {
  3059. require:'ngModel',
  3060. link:function (originalScope, element, attrs, modelCtrl) {
  3061. //SUPPORTED ATTRIBUTES (OPTIONS)
  3062. //minimal no of characters that needs to be entered before typeahead kicks-in
  3063. var minSearch = originalScope.$eval(attrs.typeaheadMinLength) || 1;
  3064. //minimal wait time after last character typed before typehead kicks-in
  3065. var waitTime = originalScope.$eval(attrs.typeaheadWaitMs) || 0;
  3066. //should it restrict model values to the ones selected from the popup only?
  3067. var isEditable = originalScope.$eval(attrs.typeaheadEditable) !== false;
  3068. //binding to a variable that indicates if matches are being retrieved asynchronously
  3069. var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop;
  3070. //a callback executed when a match is selected
  3071. var onSelectCallback = $parse(attrs.typeaheadOnSelect);
  3072. var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined;
  3073. var appendToBody = attrs.typeaheadAppendToBody ? originalScope.$eval(attrs.typeaheadAppendToBody) : false;
  3074. var focusFirst = originalScope.$eval(attrs.typeaheadFocusFirst) !== false;
  3075. //INTERNAL VARIABLES
  3076. //model setter executed upon match selection
  3077. var $setModelValue = $parse(attrs.ngModel).assign;
  3078. //expressions used by typeahead
  3079. var parserResult = typeaheadParser.parse(attrs.typeahead);
  3080. var hasFocus;
  3081. //create a child scope for the typeahead directive so we are not polluting original scope
  3082. //with typeahead-specific data (matches, query etc.)
  3083. var scope = originalScope.$new();
  3084. originalScope.$on('$destroy', function(){
  3085. scope.$destroy();
  3086. });
  3087. // WAI-ARIA
  3088. var popupId = 'typeahead-' + scope.$id + '-' + Math.floor(Math.random() * 10000);
  3089. element.attr({
  3090. 'aria-autocomplete': 'list',
  3091. 'aria-expanded': false,
  3092. 'aria-owns': popupId
  3093. });
  3094. //pop-up element used to display matches
  3095. var popUpEl = angular.element('<div typeahead-popup></div>');
  3096. popUpEl.attr({
  3097. id: popupId,
  3098. matches: 'matches',
  3099. active: 'activeIdx',
  3100. select: 'select(activeIdx)',
  3101. query: 'query',
  3102. position: 'position'
  3103. });
  3104. //custom item template
  3105. if (angular.isDefined(attrs.typeaheadTemplateUrl)) {
  3106. popUpEl.attr('template-url', attrs.typeaheadTemplateUrl);
  3107. }
  3108. var resetMatches = function() {
  3109. scope.matches = [];
  3110. scope.activeIdx = -1;
  3111. element.attr('aria-expanded', false);
  3112. };
  3113. var getMatchId = function(index) {
  3114. return popupId + '-option-' + index;
  3115. };
  3116. // Indicate that the specified match is the active (pre-selected) item in the list owned by this typeahead.
  3117. // This attribute is added or removed automatically when the `activeIdx` changes.
  3118. scope.$watch('activeIdx', function(index) {
  3119. if (index < 0) {
  3120. element.removeAttr('aria-activedescendant');
  3121. } else {
  3122. element.attr('aria-activedescendant', getMatchId(index));
  3123. }
  3124. });
  3125. var getMatchesAsync = function(inputValue) {
  3126. var locals = {$viewValue: inputValue};
  3127. isLoadingSetter(originalScope, true);
  3128. $q.when(parserResult.source(originalScope, locals)).then(function(matches) {
  3129. //it might happen that several async queries were in progress if a user were typing fast
  3130. //but we are interested only in responses that correspond to the current view value
  3131. var onCurrentRequest = (inputValue === modelCtrl.$viewValue);
  3132. if (onCurrentRequest && hasFocus) {
  3133. if (matches.length > 0) {
  3134. scope.activeIdx = focusFirst ? 0 : -1;
  3135. scope.matches.length = 0;
  3136. //transform labels
  3137. for(var i=0; i<matches.length; i++) {
  3138. locals[parserResult.itemName] = matches[i];
  3139. scope.matches.push({
  3140. id: getMatchId(i),
  3141. label: parserResult.viewMapper(scope, locals),
  3142. model: matches[i]
  3143. });
  3144. }
  3145. scope.query = inputValue;
  3146. //position pop-up with matches - we need to re-calculate its position each time we are opening a window
  3147. //with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page
  3148. //due to other elements being rendered
  3149. scope.position = appendToBody ? $position.offset(element) : $position.position(element);
  3150. scope.position.top = scope.position.top + element.prop('offsetHeight');
  3151. element.attr('aria-expanded', true);
  3152. } else {
  3153. resetMatches();
  3154. }
  3155. }
  3156. if (onCurrentRequest) {
  3157. isLoadingSetter(originalScope, false);
  3158. }
  3159. }, function(){
  3160. resetMatches();
  3161. isLoadingSetter(originalScope, false);
  3162. });
  3163. };
  3164. resetMatches();
  3165. //we need to propagate user's query so we can higlight matches
  3166. scope.query = undefined;
  3167. //Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later
  3168. var timeoutPromise;
  3169. var scheduleSearchWithTimeout = function(inputValue) {
  3170. timeoutPromise = $timeout(function () {
  3171. getMatchesAsync(inputValue);
  3172. }, waitTime);
  3173. };
  3174. var cancelPreviousTimeout = function() {
  3175. if (timeoutPromise) {
  3176. $timeout.cancel(timeoutPromise);
  3177. }
  3178. };
  3179. //plug into $parsers pipeline to open a typeahead on view changes initiated from DOM
  3180. //$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue
  3181. modelCtrl.$parsers.unshift(function (inputValue) {
  3182. hasFocus = true;
  3183. if (inputValue && inputValue.length >= minSearch) {
  3184. if (waitTime > 0) {
  3185. cancelPreviousTimeout();
  3186. scheduleSearchWithTimeout(inputValue);
  3187. } else {
  3188. getMatchesAsync(inputValue);
  3189. }
  3190. } else {
  3191. isLoadingSetter(originalScope, false);
  3192. cancelPreviousTimeout();
  3193. resetMatches();
  3194. }
  3195. if (isEditable) {
  3196. return inputValue;
  3197. } else {
  3198. if (!inputValue) {
  3199. // Reset in case user had typed something previously.
  3200. modelCtrl.$setValidity('editable', true);
  3201. return inputValue;
  3202. } else {
  3203. modelCtrl.$setValidity('editable', false);
  3204. return undefined;
  3205. }
  3206. }
  3207. });
  3208. modelCtrl.$formatters.push(function (modelValue) {
  3209. var candidateViewValue, emptyViewValue;
  3210. var locals = {};
  3211. if (inputFormatter) {
  3212. locals.$model = modelValue;
  3213. return inputFormatter(originalScope, locals);
  3214. } else {
  3215. //it might happen that we don't have enough info to properly render input value
  3216. //we need to check for this situation and simply return model value if we can't apply custom formatting
  3217. locals[parserResult.itemName] = modelValue;
  3218. candidateViewValue = parserResult.viewMapper(originalScope, locals);
  3219. locals[parserResult.itemName] = undefined;
  3220. emptyViewValue = parserResult.viewMapper(originalScope, locals);
  3221. return candidateViewValue!== emptyViewValue ? candidateViewValue : modelValue;
  3222. }
  3223. });
  3224. scope.select = function (activeIdx) {
  3225. //called from within the $digest() cycle
  3226. var locals = {};
  3227. var model, item;
  3228. locals[parserResult.itemName] = item = scope.matches[activeIdx].model;
  3229. model = parserResult.modelMapper(originalScope, locals);
  3230. $setModelValue(originalScope, model);
  3231. modelCtrl.$setValidity('editable', true);
  3232. onSelectCallback(originalScope, {
  3233. $item: item,
  3234. $model: model,
  3235. $label: parserResult.viewMapper(originalScope, locals)
  3236. });
  3237. resetMatches();
  3238. //return focus to the input element if a match was selected via a mouse click event
  3239. // use timeout to avoid $rootScope:inprog error
  3240. $timeout(function() { element[0].focus(); }, 0, false);
  3241. };
  3242. //bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27)
  3243. element.bind('keydown', function (evt) {
  3244. //typeahead is open and an "interesting" key was pressed
  3245. if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) {
  3246. return;
  3247. }
  3248. // if there's nothing selected (i.e. focusFirst) and enter is hit, don't do anything
  3249. if (scope.activeIdx == -1 && (evt.which === 13 || evt.which === 9)) {
  3250. return;
  3251. }
  3252. evt.preventDefault();
  3253. if (evt.which === 40) {
  3254. scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length;
  3255. scope.$digest();
  3256. } else if (evt.which === 38) {
  3257. scope.activeIdx = (scope.activeIdx > 0 ? scope.activeIdx : scope.matches.length) - 1;
  3258. scope.$digest();
  3259. } else if (evt.which === 13 || evt.which === 9) {
  3260. scope.$apply(function () {
  3261. scope.select(scope.activeIdx);
  3262. });
  3263. } else if (evt.which === 27) {
  3264. evt.stopPropagation();
  3265. resetMatches();
  3266. scope.$digest();
  3267. }
  3268. });
  3269. element.bind('blur', function (evt) {
  3270. hasFocus = false;
  3271. });
  3272. // Keep reference to click handler to unbind it.
  3273. var dismissClickHandler = function (evt) {
  3274. if (element[0] !== evt.target) {
  3275. resetMatches();
  3276. scope.$digest();
  3277. }
  3278. };
  3279. $document.bind('click', dismissClickHandler);
  3280. originalScope.$on('$destroy', function(){
  3281. $document.unbind('click', dismissClickHandler);
  3282. if (appendToBody) {
  3283. $popup.remove();
  3284. }
  3285. });
  3286. var $popup = $compile(popUpEl)(scope);
  3287. if (appendToBody) {
  3288. $document.find('body').append($popup);
  3289. } else {
  3290. element.after($popup);
  3291. }
  3292. }
  3293. };
  3294. }])
  3295. .directive('typeaheadPopup', function () {
  3296. return {
  3297. restrict:'EA',
  3298. scope:{
  3299. matches:'=',
  3300. query:'=',
  3301. active:'=',
  3302. position:'=',
  3303. select:'&'
  3304. },
  3305. replace:true,
  3306. templateUrl:'template/typeahead/typeahead-popup.html',
  3307. link:function (scope, element, attrs) {
  3308. scope.templateUrl = attrs.templateUrl;
  3309. scope.isOpen = function () {
  3310. return scope.matches.length > 0;
  3311. };
  3312. scope.isActive = function (matchIdx) {
  3313. return scope.active == matchIdx;
  3314. };
  3315. scope.selectActive = function (matchIdx) {
  3316. scope.active = matchIdx;
  3317. };
  3318. scope.selectMatch = function (activeIdx) {
  3319. scope.select({activeIdx:activeIdx});
  3320. };
  3321. }
  3322. };
  3323. })
  3324. .directive('typeaheadMatch', ['$http', '$templateCache', '$compile', '$parse', function ($http, $templateCache, $compile, $parse) {
  3325. return {
  3326. restrict:'EA',
  3327. scope:{
  3328. index:'=',
  3329. match:'=',
  3330. query:'='
  3331. },
  3332. link:function (scope, element, attrs) {
  3333. var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'template/typeahead/typeahead-match.html';
  3334. $http.get(tplUrl, {cache: $templateCache}).success(function(tplContent){
  3335. element.replaceWith($compile(tplContent.trim())(scope));
  3336. });
  3337. }
  3338. };
  3339. }])
  3340. .filter('typeaheadHighlight', function() {
  3341. function escapeRegexp(queryToEscape) {
  3342. return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
  3343. }
  3344. return function(matchItem, query) {
  3345. return query ? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem;
  3346. };
  3347. });