ui-utils.js 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055
  1. /**
  2. * angular-ui-utils - Swiss-Army-Knife of AngularJS tools (with no external dependencies!)
  3. * @version v0.1.1 - 2014-02-05
  4. * @link http://angular-ui.github.com
  5. * @license MIT License, http://www.opensource.org/licenses/MIT
  6. */
  7. 'use strict';
  8. angular.module('ui.alias', []).config(['$compileProvider', 'uiAliasConfig', function($compileProvider, uiAliasConfig){
  9. uiAliasConfig = uiAliasConfig || {};
  10. angular.forEach(uiAliasConfig, function(config, alias){
  11. if (angular.isString(config)) {
  12. config = {
  13. replace: true,
  14. template: config
  15. };
  16. }
  17. $compileProvider.directive(alias, function(){
  18. return config;
  19. });
  20. });
  21. }]);
  22. 'use strict';
  23. /**
  24. * General-purpose Event binding. Bind any event not natively supported by Angular
  25. * Pass an object with keynames for events to ui-event
  26. * Allows $event object and $params object to be passed
  27. *
  28. * @example <input ui-event="{ focus : 'counter++', blur : 'someCallback()' }">
  29. * @example <input ui-event="{ myCustomEvent : 'myEventHandler($event, $params)'}">
  30. *
  31. * @param ui-event {string|object literal} The event to bind to as a string or a hash of events with their callbacks
  32. */
  33. angular.module('ui.event',[]).directive('uiEvent', ['$parse',
  34. function ($parse) {
  35. return function ($scope, elm, attrs) {
  36. var events = $scope.$eval(attrs.uiEvent);
  37. angular.forEach(events, function (uiEvent, eventName) {
  38. var fn = $parse(uiEvent);
  39. elm.bind(eventName, function (evt) {
  40. var params = Array.prototype.slice.call(arguments);
  41. //Take out first paramater (event object);
  42. params = params.splice(1);
  43. fn($scope, {$event: evt, $params: params});
  44. if (!$scope.$$phase) {
  45. $scope.$apply();
  46. }
  47. });
  48. });
  49. };
  50. }]);
  51. 'use strict';
  52. /**
  53. * A replacement utility for internationalization very similar to sprintf.
  54. *
  55. * @param replace {mixed} The tokens to replace depends on type
  56. * string: all instances of $0 will be replaced
  57. * array: each instance of $0, $1, $2 etc. will be placed with each array item in corresponding order
  58. * object: all attributes will be iterated through, with :key being replaced with its corresponding value
  59. * @return string
  60. *
  61. * @example: 'Hello :name, how are you :day'.format({ name:'John', day:'Today' })
  62. * @example: 'Records $0 to $1 out of $2 total'.format(['10', '20', '3000'])
  63. * @example: '$0 agrees to all mentions $0 makes in the event that $0 hits a tree while $0 is driving drunk'.format('Bob')
  64. */
  65. angular.module('ui.format',[]).filter('format', function(){
  66. return function(value, replace) {
  67. var target = value;
  68. if (angular.isString(target) && replace !== undefined) {
  69. if (!angular.isArray(replace) && !angular.isObject(replace)) {
  70. replace = [replace];
  71. }
  72. if (angular.isArray(replace)) {
  73. var rlen = replace.length;
  74. var rfx = function (str, i) {
  75. i = parseInt(i, 10);
  76. return (i>=0 && i<rlen) ? replace[i] : str;
  77. };
  78. target = target.replace(/\$([0-9]+)/g, rfx);
  79. }
  80. else {
  81. angular.forEach(replace, function(value, key){
  82. target = target.split(':'+key).join(value);
  83. });
  84. }
  85. }
  86. return target;
  87. };
  88. });
  89. 'use strict';
  90. /**
  91. * Wraps the
  92. * @param text {string} haystack to search through
  93. * @param search {string} needle to search for
  94. * @param [caseSensitive] {boolean} optional boolean to use case-sensitive searching
  95. */
  96. angular.module('ui.highlight',[]).filter('highlight', function () {
  97. return function (text, search, caseSensitive) {
  98. if (search || angular.isNumber(search)) {
  99. text = text.toString();
  100. search = search.toString();
  101. if (caseSensitive) {
  102. return text.split(search).join('<span class="ui-match">' + search + '</span>');
  103. } else {
  104. return text.replace(new RegExp(search, 'gi'), '<span class="ui-match">$&</span>');
  105. }
  106. } else {
  107. return text;
  108. }
  109. };
  110. });
  111. 'use strict';
  112. // modeled after: angular-1.0.7/src/ng/directive/ngInclude.js
  113. angular.module('ui.include',[])
  114. .directive('uiInclude', ['$http', '$templateCache', '$anchorScroll', '$compile',
  115. function($http, $templateCache, $anchorScroll, $compile) {
  116. return {
  117. restrict: 'ECA',
  118. terminal: true,
  119. compile: function(element, attr) {
  120. var srcExp = attr.uiInclude || attr.src,
  121. fragExp = attr.fragment || '',
  122. onloadExp = attr.onload || '',
  123. autoScrollExp = attr.autoscroll;
  124. return function(scope, element) {
  125. var changeCounter = 0,
  126. childScope;
  127. var clearContent = function() {
  128. if (childScope) {
  129. childScope.$destroy();
  130. childScope = null;
  131. }
  132. element.html('');
  133. };
  134. function ngIncludeWatchAction() {
  135. var thisChangeId = ++changeCounter;
  136. var src = scope.$eval(srcExp);
  137. var fragment = scope.$eval(fragExp);
  138. if (src) {
  139. $http.get(src, {cache: $templateCache}).success(function(response) {
  140. if (thisChangeId !== changeCounter) { return; }
  141. if (childScope) { childScope.$destroy(); }
  142. childScope = scope.$new();
  143. var contents;
  144. if (fragment) {
  145. contents = angular.element('<div/>').html(response).find(fragment);
  146. }
  147. else {
  148. contents = angular.element('<div/>').html(response).contents();
  149. }
  150. element.html(contents);
  151. $compile(contents)(childScope);
  152. if (angular.isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  153. $anchorScroll();
  154. }
  155. childScope.$emit('$includeContentLoaded');
  156. scope.$eval(onloadExp);
  157. }).error(function() {
  158. if (thisChangeId === changeCounter) { clearContent(); }
  159. });
  160. } else { clearContent(); }
  161. }
  162. scope.$watch(fragExp, ngIncludeWatchAction);
  163. scope.$watch(srcExp, ngIncludeWatchAction);
  164. };
  165. }
  166. };
  167. }]);
  168. 'use strict';
  169. /**
  170. * Provides an easy way to toggle a checkboxes indeterminate property
  171. *
  172. * @example <input type="checkbox" ui-indeterminate="isUnkown">
  173. */
  174. angular.module('ui.indeterminate',[]).directive('uiIndeterminate', [
  175. function () {
  176. return {
  177. compile: function(tElm, tAttrs) {
  178. if (!tAttrs.type || tAttrs.type.toLowerCase() !== 'checkbox') {
  179. return angular.noop;
  180. }
  181. return function ($scope, elm, attrs) {
  182. $scope.$watch(attrs.uiIndeterminate, function(newVal) {
  183. elm[0].indeterminate = !!newVal;
  184. });
  185. };
  186. }
  187. };
  188. }]);
  189. 'use strict';
  190. /**
  191. * Converts variable-esque naming conventions to something presentational, capitalized words separated by space.
  192. * @param {String} value The value to be parsed and prettified.
  193. * @param {String} [inflector] The inflector to use. Default: humanize.
  194. * @return {String}
  195. * @example {{ 'Here Is my_phoneNumber' | inflector:'humanize' }} => Here Is My Phone Number
  196. * {{ 'Here Is my_phoneNumber' | inflector:'underscore' }} => here_is_my_phone_number
  197. * {{ 'Here Is my_phoneNumber' | inflector:'variable' }} => hereIsMyPhoneNumber
  198. */
  199. angular.module('ui.inflector',[]).filter('inflector', function () {
  200. function ucwords(text) {
  201. return text.replace(/^([a-z])|\s+([a-z])/g, function ($1) {
  202. return $1.toUpperCase();
  203. });
  204. }
  205. function breakup(text, separator) {
  206. return text.replace(/[A-Z]/g, function (match) {
  207. return separator + match;
  208. });
  209. }
  210. var inflectors = {
  211. humanize: function (value) {
  212. return ucwords(breakup(value, ' ').split('_').join(' '));
  213. },
  214. underscore: function (value) {
  215. return value.substr(0, 1).toLowerCase() + breakup(value.substr(1), '_').toLowerCase().split(' ').join('_');
  216. },
  217. variable: function (value) {
  218. value = value.substr(0, 1).toLowerCase() + ucwords(value.split('_').join(' ')).substr(1).split(' ').join('');
  219. return value;
  220. }
  221. };
  222. return function (text, inflector) {
  223. if (inflector !== false && angular.isString(text)) {
  224. inflector = inflector || 'humanize';
  225. return inflectors[inflector](text);
  226. } else {
  227. return text;
  228. }
  229. };
  230. });
  231. 'use strict';
  232. /**
  233. * General-purpose jQuery wrapper. Simply pass the plugin name as the expression.
  234. *
  235. * It is possible to specify a default set of parameters for each jQuery plugin.
  236. * Under the jq key, namespace each plugin by that which will be passed to ui-jq.
  237. * Unfortunately, at this time you can only pre-define the first parameter.
  238. * @example { jq : { datepicker : { showOn:'click' } } }
  239. *
  240. * @param ui-jq {string} The $elm.[pluginName]() to call.
  241. * @param [ui-options] {mixed} Expression to be evaluated and passed as options to the function
  242. * Multiple parameters can be separated by commas
  243. * @param [ui-refresh] {expression} Watch expression and refire plugin on changes
  244. *
  245. * @example <input ui-jq="datepicker" ui-options="{showOn:'click'},secondParameter,thirdParameter" ui-refresh="iChange">
  246. */
  247. angular.module('ui.jq',[]).
  248. value('uiJqConfig',{}).
  249. directive('uiJq', ['uiJqConfig', '$timeout', function uiJqInjectingFunction(uiJqConfig, $timeout) {
  250. return {
  251. restrict: 'A',
  252. compile: function uiJqCompilingFunction(tElm, tAttrs) {
  253. if (!angular.isFunction(tElm[tAttrs.uiJq])) {
  254. throw new Error('ui-jq: The "' + tAttrs.uiJq + '" function does not exist');
  255. }
  256. var options = uiJqConfig && uiJqConfig[tAttrs.uiJq];
  257. return function uiJqLinkingFunction(scope, elm, attrs) {
  258. var linkOptions = [];
  259. // If ui-options are passed, merge (or override) them onto global defaults and pass to the jQuery method
  260. if (attrs.uiOptions) {
  261. linkOptions = scope.$eval('[' + attrs.uiOptions + ']');
  262. if (angular.isObject(options) && angular.isObject(linkOptions[0])) {
  263. linkOptions[0] = angular.extend({}, options, linkOptions[0]);
  264. }
  265. } else if (options) {
  266. linkOptions = [options];
  267. }
  268. // If change compatibility is enabled, the form input's "change" event will trigger an "input" event
  269. if (attrs.ngModel && elm.is('select,input,textarea')) {
  270. elm.bind('change', function() {
  271. elm.trigger('input');
  272. });
  273. }
  274. // Call jQuery method and pass relevant options
  275. function callPlugin() {
  276. $timeout(function() {
  277. elm[attrs.uiJq].apply(elm, linkOptions);
  278. }, 0, false);
  279. }
  280. // If ui-refresh is used, re-fire the the method upon every change
  281. if (attrs.uiRefresh) {
  282. scope.$watch(attrs.uiRefresh, function() {
  283. callPlugin();
  284. });
  285. }
  286. callPlugin();
  287. };
  288. }
  289. };
  290. }]);
  291. 'use strict';
  292. angular.module('ui.keypress',[]).
  293. factory('keypressHelper', ['$parse', function keypress($parse){
  294. var keysByCode = {
  295. 8: 'backspace',
  296. 9: 'tab',
  297. 13: 'enter',
  298. 27: 'esc',
  299. 32: 'space',
  300. 33: 'pageup',
  301. 34: 'pagedown',
  302. 35: 'end',
  303. 36: 'home',
  304. 37: 'left',
  305. 38: 'up',
  306. 39: 'right',
  307. 40: 'down',
  308. 45: 'insert',
  309. 46: 'delete'
  310. };
  311. var capitaliseFirstLetter = function (string) {
  312. return string.charAt(0).toUpperCase() + string.slice(1);
  313. };
  314. return function(mode, scope, elm, attrs) {
  315. var params, combinations = [];
  316. params = scope.$eval(attrs['ui'+capitaliseFirstLetter(mode)]);
  317. // Prepare combinations for simple checking
  318. angular.forEach(params, function (v, k) {
  319. var combination, expression;
  320. expression = $parse(v);
  321. angular.forEach(k.split(' '), function(variation) {
  322. combination = {
  323. expression: expression,
  324. keys: {}
  325. };
  326. angular.forEach(variation.split('-'), function (value) {
  327. combination.keys[value] = true;
  328. });
  329. combinations.push(combination);
  330. });
  331. });
  332. // Check only matching of pressed keys one of the conditions
  333. elm.bind(mode, function (event) {
  334. // No need to do that inside the cycle
  335. var metaPressed = !!(event.metaKey && !event.ctrlKey);
  336. var altPressed = !!event.altKey;
  337. var ctrlPressed = !!event.ctrlKey;
  338. var shiftPressed = !!event.shiftKey;
  339. var keyCode = event.keyCode;
  340. // normalize keycodes
  341. if (mode === 'keypress' && !shiftPressed && keyCode >= 97 && keyCode <= 122) {
  342. keyCode = keyCode - 32;
  343. }
  344. // Iterate over prepared combinations
  345. angular.forEach(combinations, function (combination) {
  346. var mainKeyPressed = combination.keys[keysByCode[keyCode]] || combination.keys[keyCode.toString()];
  347. var metaRequired = !!combination.keys.meta;
  348. var altRequired = !!combination.keys.alt;
  349. var ctrlRequired = !!combination.keys.ctrl;
  350. var shiftRequired = !!combination.keys.shift;
  351. if (
  352. mainKeyPressed &&
  353. ( metaRequired === metaPressed ) &&
  354. ( altRequired === altPressed ) &&
  355. ( ctrlRequired === ctrlPressed ) &&
  356. ( shiftRequired === shiftPressed )
  357. ) {
  358. // Run the function
  359. scope.$apply(function () {
  360. combination.expression(scope, { '$event': event });
  361. });
  362. }
  363. });
  364. });
  365. };
  366. }]);
  367. /**
  368. * Bind one or more handlers to particular keys or their combination
  369. * @param hash {mixed} keyBindings Can be an object or string where keybinding expression of keys or keys combinations and AngularJS Exspressions are set. Object syntax: "{ keys1: expression1 [, keys2: expression2 [ , ... ]]}". String syntax: ""expression1 on keys1 [ and expression2 on keys2 [ and ... ]]"". Expression is an AngularJS Expression, and key(s) are dash-separated combinations of keys and modifiers (one or many, if any. Order does not matter). Supported modifiers are 'ctrl', 'shift', 'alt' and key can be used either via its keyCode (13 for Return) or name. Named keys are 'backspace', 'tab', 'enter', 'esc', 'space', 'pageup', 'pagedown', 'end', 'home', 'left', 'up', 'right', 'down', 'insert', 'delete'.
  370. * @example <input ui-keypress="{enter:'x = 1', 'ctrl-shift-space':'foo()', 'shift-13':'bar()'}" /> <input ui-keypress="foo = 2 on ctrl-13 and bar('hello') on shift-esc" />
  371. **/
  372. angular.module('ui.keypress').directive('uiKeydown', ['keypressHelper', function(keypressHelper){
  373. return {
  374. link: function (scope, elm, attrs) {
  375. keypressHelper('keydown', scope, elm, attrs);
  376. }
  377. };
  378. }]);
  379. angular.module('ui.keypress').directive('uiKeypress', ['keypressHelper', function(keypressHelper){
  380. return {
  381. link: function (scope, elm, attrs) {
  382. keypressHelper('keypress', scope, elm, attrs);
  383. }
  384. };
  385. }]);
  386. angular.module('ui.keypress').directive('uiKeyup', ['keypressHelper', function(keypressHelper){
  387. return {
  388. link: function (scope, elm, attrs) {
  389. keypressHelper('keyup', scope, elm, attrs);
  390. }
  391. };
  392. }]);
  393. 'use strict';
  394. /*
  395. Attaches input mask onto input element
  396. */
  397. angular.module('ui.mask', [])
  398. .value('uiMaskConfig', {
  399. 'maskDefinitions': {
  400. '9': /\d/,
  401. 'A': /[a-zA-Z]/,
  402. '*': /[a-zA-Z0-9]/
  403. }
  404. })
  405. .directive('uiMask', ['uiMaskConfig', function (maskConfig) {
  406. return {
  407. priority: 100,
  408. require: 'ngModel',
  409. restrict: 'A',
  410. compile: function uiMaskCompilingFunction(){
  411. var options = maskConfig;
  412. return function uiMaskLinkingFunction(scope, iElement, iAttrs, controller){
  413. var maskProcessed = false, eventsBound = false,
  414. maskCaretMap, maskPatterns, maskPlaceholder, maskComponents,
  415. // Minimum required length of the value to be considered valid
  416. minRequiredLength,
  417. value, valueMasked, isValid,
  418. // Vars for initializing/uninitializing
  419. originalPlaceholder = iAttrs.placeholder,
  420. originalMaxlength = iAttrs.maxlength,
  421. // Vars used exclusively in eventHandler()
  422. oldValue, oldValueUnmasked, oldCaretPosition, oldSelectionLength;
  423. function initialize(maskAttr){
  424. if (!angular.isDefined(maskAttr)) {
  425. return uninitialize();
  426. }
  427. processRawMask(maskAttr);
  428. if (!maskProcessed) {
  429. return uninitialize();
  430. }
  431. initializeElement();
  432. bindEventListeners();
  433. return true;
  434. }
  435. function initPlaceholder(placeholderAttr) {
  436. if(! angular.isDefined(placeholderAttr)) {
  437. return;
  438. }
  439. maskPlaceholder = placeholderAttr;
  440. // If the mask is processed, then we need to update the value
  441. if (maskProcessed) {
  442. eventHandler();
  443. }
  444. }
  445. function formatter(fromModelValue){
  446. if (!maskProcessed) {
  447. return fromModelValue;
  448. }
  449. value = unmaskValue(fromModelValue || '');
  450. isValid = validateValue(value);
  451. controller.$setValidity('mask', isValid);
  452. return isValid && value.length ? maskValue(value) : undefined;
  453. }
  454. function parser(fromViewValue){
  455. if (!maskProcessed) {
  456. return fromViewValue;
  457. }
  458. value = unmaskValue(fromViewValue || '');
  459. isValid = validateValue(value);
  460. // We have to set viewValue manually as the reformatting of the input
  461. // value performed by eventHandler() doesn't happen until after
  462. // this parser is called, which causes what the user sees in the input
  463. // to be out-of-sync with what the controller's $viewValue is set to.
  464. controller.$viewValue = value.length ? maskValue(value) : '';
  465. controller.$setValidity('mask', isValid);
  466. if (value === '' && controller.$error.required !== undefined) {
  467. controller.$setValidity('required', false);
  468. }
  469. return isValid ? value : undefined;
  470. }
  471. var linkOptions = {};
  472. if (iAttrs.uiOptions) {
  473. linkOptions = scope.$eval('[' + iAttrs.uiOptions + ']');
  474. if (angular.isObject(linkOptions[0])) {
  475. // we can't use angular.copy nor angular.extend, they lack the power to do a deep merge
  476. linkOptions = (function(original, current){
  477. for(var i in original) {
  478. if (Object.prototype.hasOwnProperty.call(original, i)) {
  479. if (!current[i]) {
  480. current[i] = angular.copy(original[i]);
  481. } else {
  482. angular.extend(current[i], original[i]);
  483. }
  484. }
  485. }
  486. return current;
  487. })(options, linkOptions[0]);
  488. }
  489. } else {
  490. linkOptions = options;
  491. }
  492. iAttrs.$observe('uiMask', initialize);
  493. iAttrs.$observe('placeholder', initPlaceholder);
  494. controller.$formatters.push(formatter);
  495. controller.$parsers.push(parser);
  496. function uninitialize(){
  497. maskProcessed = false;
  498. unbindEventListeners();
  499. if (angular.isDefined(originalPlaceholder)) {
  500. iElement.attr('placeholder', originalPlaceholder);
  501. } else {
  502. iElement.removeAttr('placeholder');
  503. }
  504. if (angular.isDefined(originalMaxlength)) {
  505. iElement.attr('maxlength', originalMaxlength);
  506. } else {
  507. iElement.removeAttr('maxlength');
  508. }
  509. iElement.val(controller.$modelValue);
  510. controller.$viewValue = controller.$modelValue;
  511. return false;
  512. }
  513. function initializeElement(){
  514. value = oldValueUnmasked = unmaskValue(controller.$modelValue || '');
  515. valueMasked = oldValue = maskValue(value);
  516. isValid = validateValue(value);
  517. var viewValue = isValid && value.length ? valueMasked : '';
  518. if (iAttrs.maxlength) { // Double maxlength to allow pasting new val at end of mask
  519. iElement.attr('maxlength', maskCaretMap[maskCaretMap.length - 1] * 2);
  520. }
  521. iElement.attr('placeholder', maskPlaceholder);
  522. iElement.val(viewValue);
  523. controller.$viewValue = viewValue;
  524. // Not using $setViewValue so we don't clobber the model value and dirty the form
  525. // without any kind of user interaction.
  526. }
  527. function bindEventListeners(){
  528. if (eventsBound) {
  529. return;
  530. }
  531. iElement.bind('blur', blurHandler);
  532. iElement.bind('mousedown mouseup', mouseDownUpHandler);
  533. iElement.bind('input keyup click focus', eventHandler);
  534. eventsBound = true;
  535. }
  536. function unbindEventListeners(){
  537. if (!eventsBound) {
  538. return;
  539. }
  540. iElement.unbind('blur', blurHandler);
  541. iElement.unbind('mousedown', mouseDownUpHandler);
  542. iElement.unbind('mouseup', mouseDownUpHandler);
  543. iElement.unbind('input', eventHandler);
  544. iElement.unbind('keyup', eventHandler);
  545. iElement.unbind('click', eventHandler);
  546. iElement.unbind('focus', eventHandler);
  547. eventsBound = false;
  548. }
  549. function validateValue(value){
  550. // Zero-length value validity is ngRequired's determination
  551. return value.length ? value.length >= minRequiredLength : true;
  552. }
  553. function unmaskValue(value){
  554. var valueUnmasked = '',
  555. maskPatternsCopy = maskPatterns.slice();
  556. // Preprocess by stripping mask components from value
  557. value = value.toString();
  558. angular.forEach(maskComponents, function (component){
  559. value = value.replace(component, '');
  560. });
  561. angular.forEach(value.split(''), function (chr){
  562. if (maskPatternsCopy.length && maskPatternsCopy[0].test(chr)) {
  563. valueUnmasked += chr;
  564. maskPatternsCopy.shift();
  565. }
  566. });
  567. return valueUnmasked;
  568. }
  569. function maskValue(unmaskedValue){
  570. var valueMasked = '',
  571. maskCaretMapCopy = maskCaretMap.slice();
  572. angular.forEach(maskPlaceholder.split(''), function (chr, i){
  573. if (unmaskedValue.length && i === maskCaretMapCopy[0]) {
  574. valueMasked += unmaskedValue.charAt(0) || '_';
  575. unmaskedValue = unmaskedValue.substr(1);
  576. maskCaretMapCopy.shift();
  577. }
  578. else {
  579. valueMasked += chr;
  580. }
  581. });
  582. return valueMasked;
  583. }
  584. function getPlaceholderChar(i) {
  585. var placeholder = iAttrs.placeholder;
  586. if (typeof placeholder !== 'undefined' && placeholder[i]) {
  587. return placeholder[i];
  588. } else {
  589. return '_';
  590. }
  591. }
  592. // Generate array of mask components that will be stripped from a masked value
  593. // before processing to prevent mask components from being added to the unmasked value.
  594. // E.g., a mask pattern of '+7 9999' won't have the 7 bleed into the unmasked value.
  595. // If a maskable char is followed by a mask char and has a mask
  596. // char behind it, we'll split it into it's own component so if
  597. // a user is aggressively deleting in the input and a char ahead
  598. // of the maskable char gets deleted, we'll still be able to strip
  599. // it in the unmaskValue() preprocessing.
  600. function getMaskComponents() {
  601. return maskPlaceholder.replace(/[_]+/g, '_').replace(/([^_]+)([a-zA-Z0-9])([^_])/g, '$1$2_$3').split('_');
  602. }
  603. function processRawMask(mask){
  604. var characterCount = 0;
  605. maskCaretMap = [];
  606. maskPatterns = [];
  607. maskPlaceholder = '';
  608. if (typeof mask === 'string') {
  609. minRequiredLength = 0;
  610. var isOptional = false,
  611. splitMask = mask.split('');
  612. angular.forEach(splitMask, function (chr, i){
  613. if (linkOptions.maskDefinitions[chr]) {
  614. maskCaretMap.push(characterCount);
  615. maskPlaceholder += getPlaceholderChar(i);
  616. maskPatterns.push(linkOptions.maskDefinitions[chr]);
  617. characterCount++;
  618. if (!isOptional) {
  619. minRequiredLength++;
  620. }
  621. }
  622. else if (chr === '?') {
  623. isOptional = true;
  624. }
  625. else {
  626. maskPlaceholder += chr;
  627. characterCount++;
  628. }
  629. });
  630. }
  631. // Caret position immediately following last position is valid.
  632. maskCaretMap.push(maskCaretMap.slice().pop() + 1);
  633. maskComponents = getMaskComponents();
  634. maskProcessed = maskCaretMap.length > 1 ? true : false;
  635. }
  636. function blurHandler(){
  637. oldCaretPosition = 0;
  638. oldSelectionLength = 0;
  639. if (!isValid || value.length === 0) {
  640. valueMasked = '';
  641. iElement.val('');
  642. scope.$apply(function (){
  643. controller.$setViewValue('');
  644. });
  645. }
  646. }
  647. function mouseDownUpHandler(e){
  648. if (e.type === 'mousedown') {
  649. iElement.bind('mouseout', mouseoutHandler);
  650. } else {
  651. iElement.unbind('mouseout', mouseoutHandler);
  652. }
  653. }
  654. iElement.bind('mousedown mouseup', mouseDownUpHandler);
  655. function mouseoutHandler(){
  656. /*jshint validthis: true */
  657. oldSelectionLength = getSelectionLength(this);
  658. iElement.unbind('mouseout', mouseoutHandler);
  659. }
  660. function eventHandler(e){
  661. /*jshint validthis: true */
  662. e = e || {};
  663. // Allows more efficient minification
  664. var eventWhich = e.which,
  665. eventType = e.type;
  666. // Prevent shift and ctrl from mucking with old values
  667. if (eventWhich === 16 || eventWhich === 91) { return;}
  668. var val = iElement.val(),
  669. valOld = oldValue,
  670. valMasked,
  671. valUnmasked = unmaskValue(val),
  672. valUnmaskedOld = oldValueUnmasked,
  673. valAltered = false,
  674. caretPos = getCaretPosition(this) || 0,
  675. caretPosOld = oldCaretPosition || 0,
  676. caretPosDelta = caretPos - caretPosOld,
  677. caretPosMin = maskCaretMap[0],
  678. caretPosMax = maskCaretMap[valUnmasked.length] || maskCaretMap.slice().shift(),
  679. selectionLenOld = oldSelectionLength || 0,
  680. isSelected = getSelectionLength(this) > 0,
  681. wasSelected = selectionLenOld > 0,
  682. // Case: Typing a character to overwrite a selection
  683. isAddition = (val.length > valOld.length) || (selectionLenOld && val.length > valOld.length - selectionLenOld),
  684. // Case: Delete and backspace behave identically on a selection
  685. isDeletion = (val.length < valOld.length) || (selectionLenOld && val.length === valOld.length - selectionLenOld),
  686. isSelection = (eventWhich >= 37 && eventWhich <= 40) && e.shiftKey, // Arrow key codes
  687. isKeyLeftArrow = eventWhich === 37,
  688. // Necessary due to "input" event not providing a key code
  689. isKeyBackspace = eventWhich === 8 || (eventType !== 'keyup' && isDeletion && (caretPosDelta === -1)),
  690. isKeyDelete = eventWhich === 46 || (eventType !== 'keyup' && isDeletion && (caretPosDelta === 0 ) && !wasSelected),
  691. // Handles cases where caret is moved and placed in front of invalid maskCaretMap position. Logic below
  692. // ensures that, on click or leftward caret placement, caret is moved leftward until directly right of
  693. // non-mask character. Also applied to click since users are (arguably) more likely to backspace
  694. // a character when clicking within a filled input.
  695. caretBumpBack = (isKeyLeftArrow || isKeyBackspace || eventType === 'click') && caretPos > caretPosMin;
  696. oldSelectionLength = getSelectionLength(this);
  697. // These events don't require any action
  698. if (isSelection || (isSelected && (eventType === 'click' || eventType === 'keyup'))) {
  699. return;
  700. }
  701. // Value Handling
  702. // ==============
  703. // User attempted to delete but raw value was unaffected--correct this grievous offense
  704. if ((eventType === 'input') && isDeletion && !wasSelected && valUnmasked === valUnmaskedOld) {
  705. while (isKeyBackspace && caretPos > caretPosMin && !isValidCaretPosition(caretPos)) {
  706. caretPos--;
  707. }
  708. while (isKeyDelete && caretPos < caretPosMax && maskCaretMap.indexOf(caretPos) === -1) {
  709. caretPos++;
  710. }
  711. var charIndex = maskCaretMap.indexOf(caretPos);
  712. // Strip out non-mask character that user would have deleted if mask hadn't been in the way.
  713. valUnmasked = valUnmasked.substring(0, charIndex) + valUnmasked.substring(charIndex + 1);
  714. valAltered = true;
  715. }
  716. // Update values
  717. valMasked = maskValue(valUnmasked);
  718. oldValue = valMasked;
  719. oldValueUnmasked = valUnmasked;
  720. iElement.val(valMasked);
  721. if (valAltered) {
  722. // We've altered the raw value after it's been $digest'ed, we need to $apply the new value.
  723. scope.$apply(function (){
  724. controller.$setViewValue(valUnmasked);
  725. });
  726. }
  727. // Caret Repositioning
  728. // ===================
  729. // Ensure that typing always places caret ahead of typed character in cases where the first char of
  730. // the input is a mask char and the caret is placed at the 0 position.
  731. if (isAddition && (caretPos <= caretPosMin)) {
  732. caretPos = caretPosMin + 1;
  733. }
  734. if (caretBumpBack) {
  735. caretPos--;
  736. }
  737. // Make sure caret is within min and max position limits
  738. caretPos = caretPos > caretPosMax ? caretPosMax : caretPos < caretPosMin ? caretPosMin : caretPos;
  739. // Scoot the caret back or forth until it's in a non-mask position and within min/max position limits
  740. while (!isValidCaretPosition(caretPos) && caretPos > caretPosMin && caretPos < caretPosMax) {
  741. caretPos += caretBumpBack ? -1 : 1;
  742. }
  743. if ((caretBumpBack && caretPos < caretPosMax) || (isAddition && !isValidCaretPosition(caretPosOld))) {
  744. caretPos++;
  745. }
  746. oldCaretPosition = caretPos;
  747. setCaretPosition(this, caretPos);
  748. }
  749. function isValidCaretPosition(pos){ return maskCaretMap.indexOf(pos) > -1; }
  750. function getCaretPosition(input){
  751. if (!input) return 0;
  752. if (input.selectionStart !== undefined) {
  753. return input.selectionStart;
  754. } else if (document.selection) {
  755. // Curse you IE
  756. input.focus();
  757. var selection = document.selection.createRange();
  758. selection.moveStart('character', -input.value.length);
  759. return selection.text.length;
  760. }
  761. return 0;
  762. }
  763. function setCaretPosition(input, pos){
  764. if (!input) return 0;
  765. if (input.offsetWidth === 0 || input.offsetHeight === 0) {
  766. return; // Input's hidden
  767. }
  768. if (input.setSelectionRange) {
  769. input.focus();
  770. input.setSelectionRange(pos, pos);
  771. }
  772. else if (input.createTextRange) {
  773. // Curse you IE
  774. var range = input.createTextRange();
  775. range.collapse(true);
  776. range.moveEnd('character', pos);
  777. range.moveStart('character', pos);
  778. range.select();
  779. }
  780. }
  781. function getSelectionLength(input){
  782. if (!input) return 0;
  783. if (input.selectionStart !== undefined) {
  784. return (input.selectionEnd - input.selectionStart);
  785. }
  786. if (document.selection) {
  787. return (document.selection.createRange().text.length);
  788. }
  789. return 0;
  790. }
  791. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
  792. if (!Array.prototype.indexOf) {
  793. Array.prototype.indexOf = function (searchElement /*, fromIndex */){
  794. if (this === null) {
  795. throw new TypeError();
  796. }
  797. var t = Object(this);
  798. var len = t.length >>> 0;
  799. if (len === 0) {
  800. return -1;
  801. }
  802. var n = 0;
  803. if (arguments.length > 1) {
  804. n = Number(arguments[1]);
  805. if (n !== n) { // shortcut for verifying if it's NaN
  806. n = 0;
  807. } else if (n !== 0 && n !== Infinity && n !== -Infinity) {
  808. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  809. }
  810. }
  811. if (n >= len) {
  812. return -1;
  813. }
  814. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  815. for (; k < len; k++) {
  816. if (k in t && t[k] === searchElement) {
  817. return k;
  818. }
  819. }
  820. return -1;
  821. };
  822. }
  823. };
  824. }
  825. };
  826. }
  827. ]);
  828. 'use strict';
  829. /**
  830. * Add a clear button to form inputs to reset their value
  831. */
  832. angular.module('ui.reset',[]).value('uiResetConfig',null).directive('uiReset', ['uiResetConfig', function (uiResetConfig) {
  833. var resetValue = null;
  834. if (uiResetConfig !== undefined){
  835. resetValue = uiResetConfig;
  836. }
  837. return {
  838. require: 'ngModel',
  839. link: function (scope, elm, attrs, ctrl) {
  840. var aElement;
  841. aElement = angular.element('<a class="ui-reset" />');
  842. elm.wrap('<span class="ui-resetwrap" />').after(aElement);
  843. aElement.bind('click', function (e) {
  844. e.preventDefault();
  845. scope.$apply(function () {
  846. if (attrs.uiReset){
  847. ctrl.$setViewValue(scope.$eval(attrs.uiReset));
  848. }else{
  849. ctrl.$setViewValue(resetValue);
  850. }
  851. ctrl.$render();
  852. });
  853. });
  854. }
  855. };
  856. }]);
  857. 'use strict';
  858. /**
  859. * Set a $uiRoute boolean to see if the current route matches
  860. */
  861. angular.module('ui.route', []).directive('uiRoute', ['$location', '$parse', function ($location, $parse) {
  862. return {
  863. restrict: 'AC',
  864. scope: true,
  865. compile: function(tElement, tAttrs) {
  866. var useProperty;
  867. if (tAttrs.uiRoute) {
  868. useProperty = 'uiRoute';
  869. } else if (tAttrs.ngHref) {
  870. useProperty = 'ngHref';
  871. } else if (tAttrs.href) {
  872. useProperty = 'href';
  873. } else {
  874. throw new Error('uiRoute missing a route or href property on ' + tElement[0]);
  875. }
  876. return function ($scope, elm, attrs) {
  877. var modelSetter = $parse(attrs.ngModel || attrs.routeModel || '$uiRoute').assign;
  878. var watcher = angular.noop;
  879. // Used by href and ngHref
  880. function staticWatcher(newVal) {
  881. var hash = newVal.indexOf('#');
  882. if (hash > -1){
  883. newVal = newVal.substr(hash + 1);
  884. }
  885. watcher = function watchHref() {
  886. modelSetter($scope, ($location.path().indexOf(newVal) > -1));
  887. };
  888. watcher();
  889. }
  890. // Used by uiRoute
  891. function regexWatcher(newVal) {
  892. var hash = newVal.indexOf('#');
  893. if (hash > -1){
  894. newVal = newVal.substr(hash + 1);
  895. }
  896. watcher = function watchRegex() {
  897. var regexp = new RegExp('^' + newVal + '$', ['i']);
  898. modelSetter($scope, regexp.test($location.path()));
  899. };
  900. watcher();
  901. }
  902. switch (useProperty) {
  903. case 'uiRoute':
  904. // if uiRoute={{}} this will be undefined, otherwise it will have a value and $observe() never gets triggered
  905. if (attrs.uiRoute){
  906. regexWatcher(attrs.uiRoute);
  907. }else{
  908. attrs.$observe('uiRoute', regexWatcher);
  909. }
  910. break;
  911. case 'ngHref':
  912. // Setup watcher() every time ngHref changes
  913. if (attrs.ngHref){
  914. staticWatcher(attrs.ngHref);
  915. }else{
  916. attrs.$observe('ngHref', staticWatcher);
  917. }
  918. break;
  919. case 'href':
  920. // Setup watcher()
  921. staticWatcher(attrs.href);
  922. }
  923. $scope.$on('$routeChangeSuccess', function(){
  924. watcher();
  925. });
  926. //Added for compatibility with ui-router
  927. $scope.$on('$stateChangeSuccess', function(){
  928. watcher();
  929. });
  930. };
  931. }
  932. };
  933. }]);
  934. 'use strict';
  935. angular.module('ui.scroll.jqlite', ['ui.scroll']).service('jqLiteExtras', [
  936. '$log', '$window', function(console, window) {
  937. return {
  938. registerFor: function(element) {
  939. var convertToPx, css, getMeasurements, getStyle, getWidthHeight, isWindow, scrollTo;
  940. css = angular.element.prototype.css;
  941. element.prototype.css = function(name, value) {
  942. var elem, self;
  943. self = this;
  944. elem = self[0];
  945. if (!(!elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style)) {
  946. return css.call(self, name, value);
  947. }
  948. };
  949. isWindow = function(obj) {
  950. return obj && obj.document && obj.location && obj.alert && obj.setInterval;
  951. };
  952. scrollTo = function(self, direction, value) {
  953. var elem, method, preserve, prop, _ref;
  954. elem = self[0];
  955. _ref = {
  956. top: ['scrollTop', 'pageYOffset', 'scrollLeft'],
  957. left: ['scrollLeft', 'pageXOffset', 'scrollTop']
  958. }[direction], method = _ref[0], prop = _ref[1], preserve = _ref[2];
  959. if (isWindow(elem)) {
  960. if (angular.isDefined(value)) {
  961. return elem.scrollTo(self[preserve].call(self), value);
  962. } else {
  963. if (prop in elem) {
  964. return elem[prop];
  965. } else {
  966. return elem.document.documentElement[method];
  967. }
  968. }
  969. } else {
  970. if (angular.isDefined(value)) {
  971. return elem[method] = value;
  972. } else {
  973. return elem[method];
  974. }
  975. }
  976. };
  977. if (window.getComputedStyle) {
  978. getStyle = function(elem) {
  979. return window.getComputedStyle(elem, null);
  980. };
  981. convertToPx = function(elem, value) {
  982. return parseFloat(value);
  983. };
  984. } else {
  985. getStyle = function(elem) {
  986. return elem.currentStyle;
  987. };
  988. convertToPx = function(elem, value) {
  989. var core_pnum, left, result, rnumnonpx, rs, rsLeft, style;
  990. core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source;
  991. rnumnonpx = new RegExp('^(' + core_pnum + ')(?!px)[a-z%]+$', 'i');
  992. if (!rnumnonpx.test(value)) {
  993. return parseFloat(value);
  994. } else {
  995. style = elem.style;
  996. left = style.left;
  997. rs = elem.runtimeStyle;
  998. rsLeft = rs && rs.left;
  999. if (rs) {
  1000. rs.left = style.left;
  1001. }
  1002. style.left = value;
  1003. result = style.pixelLeft;
  1004. style.left = left;
  1005. if (rsLeft) {
  1006. rs.left = rsLeft;
  1007. }
  1008. return result;
  1009. }
  1010. };
  1011. }
  1012. getMeasurements = function(elem, measure) {
  1013. var base, borderA, borderB, computedMarginA, computedMarginB, computedStyle, dirA, dirB, marginA, marginB, paddingA, paddingB, _ref;
  1014. if (isWindow(elem)) {
  1015. base = document.documentElement[{
  1016. height: 'clientHeight',
  1017. width: 'clientWidth'
  1018. }[measure]];
  1019. return {
  1020. base: base,
  1021. padding: 0,
  1022. border: 0,
  1023. margin: 0
  1024. };
  1025. }
  1026. _ref = {
  1027. width: [elem.offsetWidth, 'Left', 'Right'],
  1028. height: [elem.offsetHeight, 'Top', 'Bottom']
  1029. }[measure], base = _ref[0], dirA = _ref[1], dirB = _ref[2];
  1030. computedStyle = getStyle(elem);
  1031. paddingA = convertToPx(elem, computedStyle['padding' + dirA]) || 0;
  1032. paddingB = convertToPx(elem, computedStyle['padding' + dirB]) || 0;
  1033. borderA = convertToPx(elem, computedStyle['border' + dirA + 'Width']) || 0;
  1034. borderB = convertToPx(elem, computedStyle['border' + dirB + 'Width']) || 0;
  1035. computedMarginA = computedStyle['margin' + dirA];
  1036. computedMarginB = computedStyle['margin' + dirB];
  1037. marginA = convertToPx(elem, computedMarginA) || 0;
  1038. marginB = convertToPx(elem, computedMarginB) || 0;
  1039. return {
  1040. base: base,
  1041. padding: paddingA + paddingB,
  1042. border: borderA + borderB,
  1043. margin: marginA + marginB
  1044. };
  1045. };
  1046. getWidthHeight = function(elem, direction, measure) {
  1047. var computedStyle, measurements, result;
  1048. measurements = getMeasurements(elem, direction);
  1049. if (measurements.base > 0) {
  1050. return {
  1051. base: measurements.base - measurements.padding - measurements.border,
  1052. outer: measurements.base,
  1053. outerfull: measurements.base + measurements.margin
  1054. }[measure];
  1055. } else {
  1056. computedStyle = getStyle(elem);
  1057. result = computedStyle[direction];
  1058. if (result < 0 || result === null) {
  1059. result = elem.style[direction] || 0;
  1060. }
  1061. result = parseFloat(result) || 0;
  1062. return {
  1063. base: result - measurements.padding - measurements.border,
  1064. outer: result,
  1065. outerfull: result + measurements.padding + measurements.border + measurements.margin
  1066. }[measure];
  1067. }
  1068. };
  1069. return angular.forEach({
  1070. before: function(newElem) {
  1071. var children, elem, i, parent, self, _i, _ref;
  1072. self = this;
  1073. elem = self[0];
  1074. parent = self.parent();
  1075. children = parent.contents();
  1076. if (children[0] === elem) {
  1077. return parent.prepend(newElem);
  1078. } else {
  1079. for (i = _i = 1, _ref = children.length - 1; 1 <= _ref ? _i <= _ref : _i >= _ref; i = 1 <= _ref ? ++_i : --_i) {
  1080. if (children[i] === elem) {
  1081. angular.element(children[i - 1]).after(newElem);
  1082. return;
  1083. }
  1084. }
  1085. throw new Error('invalid DOM structure ' + elem.outerHTML);
  1086. }
  1087. },
  1088. height: function(value) {
  1089. var self;
  1090. self = this;
  1091. if (angular.isDefined(value)) {
  1092. if (angular.isNumber(value)) {
  1093. value = value + 'px';
  1094. }
  1095. return css.call(self, 'height', value);
  1096. } else {
  1097. return getWidthHeight(this[0], 'height', 'base');
  1098. }
  1099. },
  1100. outerHeight: function(option) {
  1101. return getWidthHeight(this[0], 'height', option ? 'outerfull' : 'outer');
  1102. },
  1103. offset: function(value) {
  1104. var box, doc, docElem, elem, self, win;
  1105. self = this;
  1106. if (arguments.length) {
  1107. if (value === void 0) {
  1108. return self;
  1109. } else {
  1110. return value;
  1111. }
  1112. }
  1113. box = {
  1114. top: 0,
  1115. left: 0
  1116. };
  1117. elem = self[0];
  1118. doc = elem && elem.ownerDocument;
  1119. if (!doc) {
  1120. return;
  1121. }
  1122. docElem = doc.documentElement;
  1123. if (elem.getBoundingClientRect) {
  1124. box = elem.getBoundingClientRect();
  1125. }
  1126. win = doc.defaultView || doc.parentWindow;
  1127. return {
  1128. top: box.top + (win.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0),
  1129. left: box.left + (win.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0)
  1130. };
  1131. },
  1132. scrollTop: function(value) {
  1133. return scrollTo(this, 'top', value);
  1134. },
  1135. scrollLeft: function(value) {
  1136. return scrollTo(this, 'left', value);
  1137. }
  1138. }, function(value, key) {
  1139. if (!element.prototype[key]) {
  1140. return element.prototype[key] = value;
  1141. }
  1142. });
  1143. }
  1144. };
  1145. }
  1146. ]).run([
  1147. '$log', '$window', 'jqLiteExtras', function(console, window, jqLiteExtras) {
  1148. if (!window.jQuery) {
  1149. return jqLiteExtras.registerFor(angular.element);
  1150. }
  1151. }
  1152. ]);
  1153. 'use strict';
  1154. /*
  1155. List of used element methods available in JQuery but not in JQuery Lite
  1156. element.before(elem)
  1157. element.height()
  1158. element.outerHeight(true)
  1159. element.height(value) = only for Top/Bottom padding elements
  1160. element.scrollTop()
  1161. element.scrollTop(value)
  1162. */
  1163. angular.module('ui.scroll', []).directive('ngScrollViewport', [
  1164. '$log', function() {
  1165. return {
  1166. controller: [
  1167. '$scope', '$element', function(scope, element) {
  1168. return element;
  1169. }
  1170. ]
  1171. };
  1172. }
  1173. ]).directive('ngScroll', [
  1174. '$log', '$injector', '$rootScope', '$timeout', function(console, $injector, $rootScope, $timeout) {
  1175. return {
  1176. require: ['?^ngScrollViewport'],
  1177. transclude: 'element',
  1178. priority: 1000,
  1179. terminal: true,
  1180. compile: function(element, attr, linker) {
  1181. return function($scope, $element, $attr, controllers) {
  1182. var adapter, adjustBuffer, adjustRowHeight, bof, bottomVisiblePos, buffer, bufferPadding, bufferSize, clipBottom, clipTop, datasource, datasourceName, enqueueFetch, eof, eventListener, fetch, finalize, first, insert, isDatasource, isLoading, itemName, loading, match, next, pending, reload, removeFromBuffer, resizeHandler, scrollHandler, scrollHeight, shouldLoadBottom, shouldLoadTop, tempScope, topVisiblePos, viewport;
  1183. match = $attr.ngScroll.match(/^\s*(\w+)\s+in\s+(\w+)\s*$/);
  1184. if (!match) {
  1185. throw new Error('Expected ngScroll in form of "item_ in _datasource_" but got "' + $attr.ngScroll + '"');
  1186. }
  1187. itemName = match[1];
  1188. datasourceName = match[2];
  1189. isDatasource = function(datasource) {
  1190. return angular.isObject(datasource) && datasource.get && angular.isFunction(datasource.get);
  1191. };
  1192. datasource = $scope[datasourceName];
  1193. if (!isDatasource(datasource)) {
  1194. datasource = $injector.get(datasourceName);
  1195. if (!isDatasource(datasource)) {
  1196. throw new Error(datasourceName + ' is not a valid datasource');
  1197. }
  1198. }
  1199. bufferSize = Math.max(3, +$attr.bufferSize || 10);
  1200. bufferPadding = function() {
  1201. return viewport.height() * Math.max(0.1, +$attr.padding || 0.1);
  1202. };
  1203. scrollHeight = function(elem) {
  1204. return elem[0].scrollHeight || elem[0].document.documentElement.scrollHeight;
  1205. };
  1206. adapter = null;
  1207. linker(tempScope = $scope.$new(), function(template) {
  1208. var bottomPadding, createPadding, padding, repeaterType, topPadding, viewport;
  1209. repeaterType = template[0].localName;
  1210. if (repeaterType === 'dl') {
  1211. throw new Error('ng-scroll directive does not support <' + template[0].localName + '> as a repeating tag: ' + template[0].outerHTML);
  1212. }
  1213. if (repeaterType !== 'li' && repeaterType !== 'tr') {
  1214. repeaterType = 'div';
  1215. }
  1216. viewport = controllers[0] || angular.element(window);
  1217. viewport.css({
  1218. 'overflow-y': 'auto',
  1219. 'display': 'block'
  1220. });
  1221. padding = function(repeaterType) {
  1222. var div, result, table;
  1223. switch (repeaterType) {
  1224. case 'tr':
  1225. table = angular.element('<table><tr><td><div></div></td></tr></table>');
  1226. div = table.find('div');
  1227. result = table.find('tr');
  1228. result.paddingHeight = function() {
  1229. return div.height.apply(div, arguments);
  1230. };
  1231. return result;
  1232. default:
  1233. result = angular.element('<' + repeaterType + '></' + repeaterType + '>');
  1234. result.paddingHeight = result.height;
  1235. return result;
  1236. }
  1237. };
  1238. createPadding = function(padding, element, direction) {
  1239. element[{
  1240. top: 'before',
  1241. bottom: 'after'
  1242. }[direction]](padding);
  1243. return {
  1244. paddingHeight: function() {
  1245. return padding.paddingHeight.apply(padding, arguments);
  1246. },
  1247. insert: function(element) {
  1248. return padding[{
  1249. top: 'after',
  1250. bottom: 'before'
  1251. }[direction]](element);
  1252. }
  1253. };
  1254. };
  1255. topPadding = createPadding(padding(repeaterType), element, 'top');
  1256. bottomPadding = createPadding(padding(repeaterType), element, 'bottom');
  1257. tempScope.$destroy();
  1258. return adapter = {
  1259. viewport: viewport,
  1260. topPadding: topPadding.paddingHeight,
  1261. bottomPadding: bottomPadding.paddingHeight,
  1262. append: bottomPadding.insert,
  1263. prepend: topPadding.insert,
  1264. bottomDataPos: function() {
  1265. return scrollHeight(viewport) - bottomPadding.paddingHeight();
  1266. },
  1267. topDataPos: function() {
  1268. return topPadding.paddingHeight();
  1269. }
  1270. };
  1271. });
  1272. viewport = adapter.viewport;
  1273. first = 1;
  1274. next = 1;
  1275. buffer = [];
  1276. pending = [];
  1277. eof = false;
  1278. bof = false;
  1279. loading = datasource.loading || function() {};
  1280. isLoading = false;
  1281. removeFromBuffer = function(start, stop) {
  1282. var i, _i;
  1283. for (i = _i = start; start <= stop ? _i < stop : _i > stop; i = start <= stop ? ++_i : --_i) {
  1284. buffer[i].scope.$destroy();
  1285. buffer[i].element.remove();
  1286. }
  1287. return buffer.splice(start, stop - start);
  1288. };
  1289. reload = function() {
  1290. first = 1;
  1291. next = 1;
  1292. removeFromBuffer(0, buffer.length);
  1293. adapter.topPadding(0);
  1294. adapter.bottomPadding(0);
  1295. pending = [];
  1296. eof = false;
  1297. bof = false;
  1298. return adjustBuffer(false);
  1299. };
  1300. bottomVisiblePos = function() {
  1301. return viewport.scrollTop() + viewport.height();
  1302. };
  1303. topVisiblePos = function() {
  1304. return viewport.scrollTop();
  1305. };
  1306. shouldLoadBottom = function() {
  1307. return !eof && adapter.bottomDataPos() < bottomVisiblePos() + bufferPadding();
  1308. };
  1309. clipBottom = function() {
  1310. var bottomHeight, i, itemHeight, overage, _i, _ref;
  1311. bottomHeight = 0;
  1312. overage = 0;
  1313. for (i = _i = _ref = buffer.length - 1; _ref <= 0 ? _i <= 0 : _i >= 0; i = _ref <= 0 ? ++_i : --_i) {
  1314. itemHeight = buffer[i].element.outerHeight(true);
  1315. if (adapter.bottomDataPos() - bottomHeight - itemHeight > bottomVisiblePos() + bufferPadding()) {
  1316. bottomHeight += itemHeight;
  1317. overage++;
  1318. eof = false;
  1319. } else {
  1320. break;
  1321. }
  1322. }
  1323. if (overage > 0) {
  1324. adapter.bottomPadding(adapter.bottomPadding() + bottomHeight);
  1325. removeFromBuffer(buffer.length - overage, buffer.length);
  1326. next -= overage;
  1327. return console.log('clipped off bottom ' + overage + ' bottom padding ' + (adapter.bottomPadding()));
  1328. }
  1329. };
  1330. shouldLoadTop = function() {
  1331. return !bof && (adapter.topDataPos() > topVisiblePos() - bufferPadding());
  1332. };
  1333. clipTop = function() {
  1334. var item, itemHeight, overage, topHeight, _i, _len;
  1335. topHeight = 0;
  1336. overage = 0;
  1337. for (_i = 0, _len = buffer.length; _i < _len; _i++) {
  1338. item = buffer[_i];
  1339. itemHeight = item.element.outerHeight(true);
  1340. if (adapter.topDataPos() + topHeight + itemHeight < topVisiblePos() - bufferPadding()) {
  1341. topHeight += itemHeight;
  1342. overage++;
  1343. bof = false;
  1344. } else {
  1345. break;
  1346. }
  1347. }
  1348. if (overage > 0) {
  1349. adapter.topPadding(adapter.topPadding() + topHeight);
  1350. removeFromBuffer(0, overage);
  1351. first += overage;
  1352. return console.log('clipped off top ' + overage + ' top padding ' + (adapter.topPadding()));
  1353. }
  1354. };
  1355. enqueueFetch = function(direction, scrolling) {
  1356. if (!isLoading) {
  1357. isLoading = true;
  1358. loading(true);
  1359. }
  1360. if (pending.push(direction) === 1) {
  1361. return fetch(scrolling);
  1362. }
  1363. };
  1364. insert = function(index, item) {
  1365. var itemScope, toBeAppended, wrapper;
  1366. itemScope = $scope.$new();
  1367. itemScope[itemName] = item;
  1368. toBeAppended = index > first;
  1369. itemScope.$index = index;
  1370. if (toBeAppended) {
  1371. itemScope.$index--;
  1372. }
  1373. wrapper = {
  1374. scope: itemScope
  1375. };
  1376. linker(itemScope, function(clone) {
  1377. wrapper.element = clone;
  1378. if (toBeAppended) {
  1379. if (index === next) {
  1380. adapter.append(clone);
  1381. return buffer.push(wrapper);
  1382. } else {
  1383. buffer[index - first].element.after(clone);
  1384. return buffer.splice(index - first + 1, 0, wrapper);
  1385. }
  1386. } else {
  1387. adapter.prepend(clone);
  1388. return buffer.unshift(wrapper);
  1389. }
  1390. });
  1391. return {
  1392. appended: toBeAppended,
  1393. wrapper: wrapper
  1394. };
  1395. };
  1396. adjustRowHeight = function(appended, wrapper) {
  1397. var newHeight;
  1398. if (appended) {
  1399. return adapter.bottomPadding(Math.max(0, adapter.bottomPadding() - wrapper.element.outerHeight(true)));
  1400. } else {
  1401. newHeight = adapter.topPadding() - wrapper.element.outerHeight(true);
  1402. if (newHeight >= 0) {
  1403. return adapter.topPadding(newHeight);
  1404. } else {
  1405. return viewport.scrollTop(viewport.scrollTop() + wrapper.element.outerHeight(true));
  1406. }
  1407. }
  1408. };
  1409. adjustBuffer = function(scrolling, newItems, finalize) {
  1410. var doAdjustment;
  1411. doAdjustment = function() {
  1412. console.log('top {actual=' + (adapter.topDataPos()) + ' visible from=' + (topVisiblePos()) + ' bottom {visible through=' + (bottomVisiblePos()) + ' actual=' + (adapter.bottomDataPos()) + '}');
  1413. if (shouldLoadBottom()) {
  1414. enqueueFetch(true, scrolling);
  1415. } else {
  1416. if (shouldLoadTop()) {
  1417. enqueueFetch(false, scrolling);
  1418. }
  1419. }
  1420. if (finalize) {
  1421. return finalize();
  1422. }
  1423. };
  1424. if (newItems) {
  1425. return $timeout(function() {
  1426. var row, _i, _len;
  1427. for (_i = 0, _len = newItems.length; _i < _len; _i++) {
  1428. row = newItems[_i];
  1429. adjustRowHeight(row.appended, row.wrapper);
  1430. }
  1431. return doAdjustment();
  1432. });
  1433. } else {
  1434. return doAdjustment();
  1435. }
  1436. };
  1437. finalize = function(scrolling, newItems) {
  1438. return adjustBuffer(scrolling, newItems, function() {
  1439. pending.shift();
  1440. if (pending.length === 0) {
  1441. isLoading = false;
  1442. return loading(false);
  1443. } else {
  1444. return fetch(scrolling);
  1445. }
  1446. });
  1447. };
  1448. fetch = function(scrolling) {
  1449. var direction;
  1450. direction = pending[0];
  1451. if (direction) {
  1452. if (buffer.length && !shouldLoadBottom()) {
  1453. return finalize(scrolling);
  1454. } else {
  1455. return datasource.get(next, bufferSize, function(result) {
  1456. var item, newItems, _i, _len;
  1457. newItems = [];
  1458. if (result.length === 0) {
  1459. eof = true;
  1460. adapter.bottomPadding(0);
  1461. console.log('appended: requested ' + bufferSize + ' records starting from ' + next + ' recieved: eof');
  1462. } else {
  1463. clipTop();
  1464. for (_i = 0, _len = result.length; _i < _len; _i++) {
  1465. item = result[_i];
  1466. newItems.push(insert(++next, item));
  1467. }
  1468. console.log('appended: requested ' + bufferSize + ' received ' + result.length + ' buffer size ' + buffer.length + ' first ' + first + ' next ' + next);
  1469. }
  1470. return finalize(scrolling, newItems);
  1471. });
  1472. }
  1473. } else {
  1474. if (buffer.length && !shouldLoadTop()) {
  1475. return finalize(scrolling);
  1476. } else {
  1477. return datasource.get(first - bufferSize, bufferSize, function(result) {
  1478. var i, newItems, _i, _ref;
  1479. newItems = [];
  1480. if (result.length === 0) {
  1481. bof = true;
  1482. adapter.topPadding(0);
  1483. console.log('prepended: requested ' + bufferSize + ' records starting from ' + (first - bufferSize) + ' recieved: bof');
  1484. } else {
  1485. clipBottom();
  1486. for (i = _i = _ref = result.length - 1; _ref <= 0 ? _i <= 0 : _i >= 0; i = _ref <= 0 ? ++_i : --_i) {
  1487. newItems.unshift(insert(--first, result[i]));
  1488. }
  1489. console.log('prepended: requested ' + bufferSize + ' received ' + result.length + ' buffer size ' + buffer.length + ' first ' + first + ' next ' + next);
  1490. }
  1491. return finalize(scrolling, newItems);
  1492. });
  1493. }
  1494. }
  1495. };
  1496. resizeHandler = function() {
  1497. if (!$rootScope.$$phase && !isLoading) {
  1498. adjustBuffer(false);
  1499. return $scope.$apply();
  1500. }
  1501. };
  1502. viewport.bind('resize', resizeHandler);
  1503. scrollHandler = function() {
  1504. if (!$rootScope.$$phase && !isLoading) {
  1505. adjustBuffer(true);
  1506. return $scope.$apply();
  1507. }
  1508. };
  1509. viewport.bind('scroll', scrollHandler);
  1510. $scope.$watch(datasource.revision, function() {
  1511. return reload();
  1512. });
  1513. if (datasource.scope) {
  1514. eventListener = datasource.scope.$new();
  1515. } else {
  1516. eventListener = $scope.$new();
  1517. }
  1518. $scope.$on('$destroy', function() {
  1519. eventListener.$destroy();
  1520. viewport.unbind('resize', resizeHandler);
  1521. return viewport.unbind('scroll', scrollHandler);
  1522. });
  1523. eventListener.$on('update.items', function(event, locator, newItem) {
  1524. var wrapper, _fn, _i, _len, _ref;
  1525. if (angular.isFunction(locator)) {
  1526. _fn = function(wrapper) {
  1527. return locator(wrapper.scope);
  1528. };
  1529. for (_i = 0, _len = buffer.length; _i < _len; _i++) {
  1530. wrapper = buffer[_i];
  1531. _fn(wrapper);
  1532. }
  1533. } else {
  1534. if ((0 <= (_ref = locator - first - 1) && _ref < buffer.length)) {
  1535. buffer[locator - first - 1].scope[itemName] = newItem;
  1536. }
  1537. }
  1538. return null;
  1539. });
  1540. eventListener.$on('delete.items', function(event, locator) {
  1541. var i, item, temp, wrapper, _fn, _i, _j, _k, _len, _len1, _len2, _ref;
  1542. if (angular.isFunction(locator)) {
  1543. temp = [];
  1544. for (_i = 0, _len = buffer.length; _i < _len; _i++) {
  1545. item = buffer[_i];
  1546. temp.unshift(item);
  1547. }
  1548. _fn = function(wrapper) {
  1549. if (locator(wrapper.scope)) {
  1550. removeFromBuffer(temp.length - 1 - i, temp.length - i);
  1551. return next--;
  1552. }
  1553. };
  1554. for (i = _j = 0, _len1 = temp.length; _j < _len1; i = ++_j) {
  1555. wrapper = temp[i];
  1556. _fn(wrapper);
  1557. }
  1558. } else {
  1559. if ((0 <= (_ref = locator - first - 1) && _ref < buffer.length)) {
  1560. removeFromBuffer(locator - first - 1, locator - first);
  1561. next--;
  1562. }
  1563. }
  1564. for (i = _k = 0, _len2 = buffer.length; _k < _len2; i = ++_k) {
  1565. item = buffer[i];
  1566. item.scope.$index = first + i;
  1567. }
  1568. return adjustBuffer(false);
  1569. });
  1570. return eventListener.$on('insert.item', function(event, locator, item) {
  1571. var i, inserted, temp, wrapper, _fn, _i, _j, _k, _len, _len1, _len2, _ref;
  1572. inserted = [];
  1573. if (angular.isFunction(locator)) {
  1574. temp = [];
  1575. for (_i = 0, _len = buffer.length; _i < _len; _i++) {
  1576. item = buffer[_i];
  1577. temp.unshift(item);
  1578. }
  1579. _fn = function(wrapper) {
  1580. var j, newItems, _k, _len2, _results;
  1581. if (newItems = locator(wrapper.scope)) {
  1582. insert = function(index, newItem) {
  1583. insert(index, newItem);
  1584. return next++;
  1585. };
  1586. if (angular.isArray(newItems)) {
  1587. _results = [];
  1588. for (j = _k = 0, _len2 = newItems.length; _k < _len2; j = ++_k) {
  1589. item = newItems[j];
  1590. _results.push(inserted.push(insert(i + j, item)));
  1591. }
  1592. return _results;
  1593. } else {
  1594. return inserted.push(insert(i, newItems));
  1595. }
  1596. }
  1597. };
  1598. for (i = _j = 0, _len1 = temp.length; _j < _len1; i = ++_j) {
  1599. wrapper = temp[i];
  1600. _fn(wrapper);
  1601. }
  1602. } else {
  1603. if ((0 <= (_ref = locator - first - 1) && _ref < buffer.length)) {
  1604. inserted.push(insert(locator, item));
  1605. next++;
  1606. }
  1607. }
  1608. for (i = _k = 0, _len2 = buffer.length; _k < _len2; i = ++_k) {
  1609. item = buffer[i];
  1610. item.scope.$index = first + i;
  1611. }
  1612. return adjustBuffer(false, inserted);
  1613. });
  1614. };
  1615. }
  1616. };
  1617. }
  1618. ]);
  1619. 'use strict';
  1620. /**
  1621. * Adds a 'ui-scrollfix' class to the element when the page scrolls past it's position.
  1622. * @param [offset] {int} optional Y-offset to override the detected offset.
  1623. * Takes 300 (absolute) or -300 or +300 (relative to detected)
  1624. */
  1625. angular.module('ui.scrollfix',[]).directive('uiScrollfix', ['$window', function ($window) {
  1626. return {
  1627. require: '^?uiScrollfixTarget',
  1628. link: function (scope, elm, attrs, uiScrollfixTarget) {
  1629. var top = elm[0].offsetTop,
  1630. $target = uiScrollfixTarget && uiScrollfixTarget.$element || angular.element($window);
  1631. if (!attrs.uiScrollfix) {
  1632. attrs.uiScrollfix = top;
  1633. } else if (typeof(attrs.uiScrollfix) === 'string') {
  1634. // charAt is generally faster than indexOf: http://jsperf.com/indexof-vs-charat
  1635. if (attrs.uiScrollfix.charAt(0) === '-') {
  1636. attrs.uiScrollfix = top - parseFloat(attrs.uiScrollfix.substr(1));
  1637. } else if (attrs.uiScrollfix.charAt(0) === '+') {
  1638. attrs.uiScrollfix = top + parseFloat(attrs.uiScrollfix.substr(1));
  1639. }
  1640. }
  1641. function onScroll() {
  1642. // if pageYOffset is defined use it, otherwise use other crap for IE
  1643. var offset;
  1644. if (angular.isDefined($window.pageYOffset)) {
  1645. offset = $window.pageYOffset;
  1646. } else {
  1647. var iebody = (document.compatMode && document.compatMode !== 'BackCompat') ? document.documentElement : document.body;
  1648. offset = iebody.scrollTop;
  1649. }
  1650. if (!elm.hasClass('ui-scrollfix') && offset > attrs.uiScrollfix) {
  1651. elm.addClass('ui-scrollfix');
  1652. } else if (elm.hasClass('ui-scrollfix') && offset < attrs.uiScrollfix) {
  1653. elm.removeClass('ui-scrollfix');
  1654. }
  1655. }
  1656. $target.on('scroll', onScroll);
  1657. // Unbind scroll event handler when directive is removed
  1658. scope.$on('$destroy', function() {
  1659. $target.off('scroll', onScroll);
  1660. });
  1661. }
  1662. };
  1663. }]).directive('uiScrollfixTarget', [function () {
  1664. return {
  1665. controller: ['$element', function($element) {
  1666. this.$element = $element;
  1667. }]
  1668. };
  1669. }]);
  1670. 'use strict';
  1671. /**
  1672. * uiShow Directive
  1673. *
  1674. * Adds a 'ui-show' class to the element instead of display:block
  1675. * Created to allow tighter control of CSS without bulkier directives
  1676. *
  1677. * @param expression {boolean} evaluated expression to determine if the class should be added
  1678. */
  1679. angular.module('ui.showhide',[])
  1680. .directive('uiShow', [function () {
  1681. return function (scope, elm, attrs) {
  1682. scope.$watch(attrs.uiShow, function (newVal) {
  1683. if (newVal) {
  1684. elm.addClass('ui-show');
  1685. } else {
  1686. elm.removeClass('ui-show');
  1687. }
  1688. });
  1689. };
  1690. }])
  1691. /**
  1692. * uiHide Directive
  1693. *
  1694. * Adds a 'ui-hide' class to the element instead of display:block
  1695. * Created to allow tighter control of CSS without bulkier directives
  1696. *
  1697. * @param expression {boolean} evaluated expression to determine if the class should be added
  1698. */
  1699. .directive('uiHide', [function () {
  1700. return function (scope, elm, attrs) {
  1701. scope.$watch(attrs.uiHide, function (newVal) {
  1702. if (newVal) {
  1703. elm.addClass('ui-hide');
  1704. } else {
  1705. elm.removeClass('ui-hide');
  1706. }
  1707. });
  1708. };
  1709. }])
  1710. /**
  1711. * uiToggle Directive
  1712. *
  1713. * Adds a class 'ui-show' if true, and a 'ui-hide' if false to the element instead of display:block/display:none
  1714. * Created to allow tighter control of CSS without bulkier directives. This also allows you to override the
  1715. * default visibility of the element using either class.
  1716. *
  1717. * @param expression {boolean} evaluated expression to determine if the class should be added
  1718. */
  1719. .directive('uiToggle', [function () {
  1720. return function (scope, elm, attrs) {
  1721. scope.$watch(attrs.uiToggle, function (newVal) {
  1722. if (newVal) {
  1723. elm.removeClass('ui-hide').addClass('ui-show');
  1724. } else {
  1725. elm.removeClass('ui-show').addClass('ui-hide');
  1726. }
  1727. });
  1728. };
  1729. }]);
  1730. 'use strict';
  1731. /**
  1732. * Filters out all duplicate items from an array by checking the specified key
  1733. * @param [key] {string} the name of the attribute of each object to compare for uniqueness
  1734. if the key is empty, the entire object will be compared
  1735. if the key === false then no filtering will be performed
  1736. * @return {array}
  1737. */
  1738. angular.module('ui.unique',[]).filter('unique', ['$parse', function ($parse) {
  1739. return function (items, filterOn) {
  1740. if (filterOn === false) {
  1741. return items;
  1742. }
  1743. if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
  1744. var newItems = [],
  1745. get = angular.isString(filterOn) ? $parse(filterOn) : function (item) { return item; };
  1746. var extractValueToCompare = function (item) {
  1747. return angular.isObject(item) ? get(item) : item;
  1748. };
  1749. angular.forEach(items, function (item) {
  1750. var isDuplicate = false;
  1751. for (var i = 0; i < newItems.length; i++) {
  1752. if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
  1753. isDuplicate = true;
  1754. break;
  1755. }
  1756. }
  1757. if (!isDuplicate) {
  1758. newItems.push(item);
  1759. }
  1760. });
  1761. items = newItems;
  1762. }
  1763. return items;
  1764. };
  1765. }]);
  1766. 'use strict';
  1767. /**
  1768. * General-purpose validator for ngModel.
  1769. * angular.js comes with several built-in validation mechanism for input fields (ngRequired, ngPattern etc.) but using
  1770. * an arbitrary validation function requires creation of a custom formatters and / or parsers.
  1771. * The ui-validate directive makes it easy to use any function(s) defined in scope as a validator function(s).
  1772. * A validator function will trigger validation on both model and input changes.
  1773. *
  1774. * @example <input ui-validate=" 'myValidatorFunction($value)' ">
  1775. * @example <input ui-validate="{ foo : '$value > anotherModel', bar : 'validateFoo($value)' }">
  1776. * @example <input ui-validate="{ foo : '$value > anotherModel' }" ui-validate-watch=" 'anotherModel' ">
  1777. * @example <input ui-validate="{ foo : '$value > anotherModel', bar : 'validateFoo($value)' }" ui-validate-watch=" { foo : 'anotherModel' } ">
  1778. *
  1779. * @param ui-validate {string|object literal} If strings is passed it should be a scope's function to be used as a validator.
  1780. * If an object literal is passed a key denotes a validation error key while a value should be a validator function.
  1781. * In both cases validator function should take a value to validate as its argument and should return true/false indicating a validation result.
  1782. */
  1783. angular.module('ui.validate',[]).directive('uiValidate', function () {
  1784. return {
  1785. restrict: 'A',
  1786. require: 'ngModel',
  1787. link: function (scope, elm, attrs, ctrl) {
  1788. var validateFn, validators = {},
  1789. validateExpr = scope.$eval(attrs.uiValidate);
  1790. if (!validateExpr){ return;}
  1791. if (angular.isString(validateExpr)) {
  1792. validateExpr = { validator: validateExpr };
  1793. }
  1794. angular.forEach(validateExpr, function (exprssn, key) {
  1795. validateFn = function (valueToValidate) {
  1796. var expression = scope.$eval(exprssn, { '$value' : valueToValidate });
  1797. if (angular.isObject(expression) && angular.isFunction(expression.then)) {
  1798. // expression is a promise
  1799. expression.then(function(){
  1800. ctrl.$setValidity(key, true);
  1801. }, function(){
  1802. ctrl.$setValidity(key, false);
  1803. });
  1804. return valueToValidate;
  1805. } else if (expression) {
  1806. // expression is true
  1807. ctrl.$setValidity(key, true);
  1808. return valueToValidate;
  1809. } else {
  1810. // expression is false
  1811. ctrl.$setValidity(key, false);
  1812. return valueToValidate;
  1813. }
  1814. };
  1815. validators[key] = validateFn;
  1816. ctrl.$formatters.push(validateFn);
  1817. ctrl.$parsers.push(validateFn);
  1818. });
  1819. function apply_watch(watch)
  1820. {
  1821. //string - update all validators on expression change
  1822. if (angular.isString(watch))
  1823. {
  1824. scope.$watch(watch, function(){
  1825. angular.forEach(validators, function(validatorFn){
  1826. validatorFn(ctrl.$modelValue);
  1827. });
  1828. });
  1829. return;
  1830. }
  1831. //array - update all validators on change of any expression
  1832. if (angular.isArray(watch))
  1833. {
  1834. angular.forEach(watch, function(expression){
  1835. scope.$watch(expression, function()
  1836. {
  1837. angular.forEach(validators, function(validatorFn){
  1838. validatorFn(ctrl.$modelValue);
  1839. });
  1840. });
  1841. });
  1842. return;
  1843. }
  1844. //object - update appropriate validator
  1845. if (angular.isObject(watch))
  1846. {
  1847. angular.forEach(watch, function(expression, validatorKey)
  1848. {
  1849. //value is string - look after one expression
  1850. if (angular.isString(expression))
  1851. {
  1852. scope.$watch(expression, function(){
  1853. validators[validatorKey](ctrl.$modelValue);
  1854. });
  1855. }
  1856. //value is array - look after all expressions in array
  1857. if (angular.isArray(expression))
  1858. {
  1859. angular.forEach(expression, function(intExpression)
  1860. {
  1861. scope.$watch(intExpression, function(){
  1862. validators[validatorKey](ctrl.$modelValue);
  1863. });
  1864. });
  1865. }
  1866. });
  1867. }
  1868. }
  1869. // Support for ui-validate-watch
  1870. if (attrs.uiValidateWatch){
  1871. apply_watch( scope.$eval(attrs.uiValidateWatch) );
  1872. }
  1873. }
  1874. };
  1875. });
  1876. angular.module('ui.utils', [
  1877. 'ui.event',
  1878. 'ui.format',
  1879. 'ui.highlight',
  1880. 'ui.include',
  1881. 'ui.indeterminate',
  1882. 'ui.inflector',
  1883. 'ui.jq',
  1884. 'ui.keypress',
  1885. 'ui.mask',
  1886. 'ui.reset',
  1887. 'ui.route',
  1888. 'ui.scrollfix',
  1889. 'ui.scroll',
  1890. 'ui.scroll.jqlite',
  1891. 'ui.showhide',
  1892. 'ui.unique',
  1893. 'ui.validate'
  1894. ]);