Advertisement
Guest User

angular.html

a guest
Jul 31st, 2016
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 36.87 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <!-- saved from url=(0110)http://htmlpreview.github.io/?https://github.com/uhlryk/angular-dynamic-number/blob/master/examples/index.html -->
  3. <html ng-app="testApp" class="ng-scope"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><style type="text/css">@charset "UTF-8";[ng\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style><!--<base href="https://raw.githubusercontent.com/uhlryk/angular-dynamic-number/master/examples/index.html">--><base href=".">
  4. <title>My Angular App</title>
  5. <link rel="stylesheet" type="text/css" href="./My Angular App_files/bootstrap.min.css">
  6. <script data-require="angular.js@1.5.0" data-semver="1.5.0" src="./My Angular App_files/angular.js"></script>
  7. <!--<script type="text/htmlpreview" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>-->
  8. <!-- <script type="text/htmlpreview" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script> -->
  9. <script type="text/htmlpreview" src="./My Angular App_files/dynamic-number.js"></script>
  10. <script>
  11. angular.module("testApp", ["dynamicNumber"])
  12. .config(['dynamicNumberStrategyProvider', function(dynamicNumberStrategyProvider){
  13. dynamicNumberStrategyProvider.addStrategy('price', {
  14. numInt: 6,
  15. numFract: 4,
  16. numSep: '.',
  17. numPos: true,
  18. numNeg: false,
  19. numRound: 'round',
  20. numThousand: true,
  21. numThousandSep: ' '
  22. });
  23. }]);
  24. </script>
  25. </head>
  26. <body>
  27. <div class="container-fluid content">
  28. <div class="row">
  29. <div class="col-sm-10 com-sm-offset-1 col-md-8 col-md-offset-2">
  30. <h1>Example of angular dynamic number directive</h1>
  31. <form name="directiveForm" class="form-horizontal ng-valid ng-dirty ng-valid-parse" ng-init="value1 = &#39;&#39;;value2 = &#39;&#39;;value3 = &#39;&#39;;value4 = &#39;&#39;;value5 = &#39;&#39;;value6 = &#39;&#39;;value7 = &#39;&#39;;value8=&#39;&#39;;value9=&#39;&#39;;value10=&#39;&#39;;value11=&#39;&#39;;;value12=&#39;&#39;;value13=&#39;&#39;;">
  32. <div class="form-group">
  33. <label class="control-label">Number may be positive or negative, decimal separator comma</label>
  34. <input type="text" ng-trim="false" ng-model="value1" class="form-control ng-pristine ng-untouched ng-valid ng-isolate-scope ng-empty" awnum="" num-sep="," num-int="4" num-fract="2" placeholder="e.g. XXXX,XX">
  35. <div class="ng-binding">How looks model: </div>
  36. </div>
  37. <div class="form-group">
  38. <label class="control-label">Number may be positive or negative, decimal separator dot, tousand separator comma</label>
  39. <input type="text" ng-trim="false" ng-model="value6" class="form-control ng-pristine ng-untouched ng-valid ng-isolate-scope ng-empty" awnum="" num-sep="." num-int="8" num-fract="4" num-thousand="true" placeholder="e.g. X,XXX.XX">
  40. <div class="ng-binding">How looks model: </div>
  41. </div>
  42. <div class="form-group">
  43. <label class="control-label">Number may be positive or negative, decimal separator comma, tousand separator dot</label>
  44. <input type="text" ng-trim="false" ng-model="value7" class="form-control ng-pristine ng-untouched ng-valid ng-isolate-scope ng-empty" awnum="" num-sep="," num-int="8" num-fract="4" num-thousand="true" placeholder="e.g. X.XXX,XX">
  45. <div class="ng-binding">How looks model: </div>
  46. </div>
  47. <div class="form-group">
  48. <label class="control-label">Number may be positive or negative, decimal separator comma, tousand separator space</label>
  49. <input type="text" ng-trim="false" ng-model="value9" class="form-control ng-pristine ng-untouched ng-valid ng-isolate-scope ng-empty" awnum="" num-sep="," num-int="8" num-fract="4" num-thousand="true" num-thousand-sep=" " placeholder="e.g. X XXX,XX">
  50. <div class="ng-binding">How looks model: </div>
  51. </div>
  52. <div class="form-group">
  53. <label class="control-label">Number may be positive or negative, decimal separator comma, tousand separator apostrophe</label>
  54. <input type="text" ng-trim="false" ng-model="value12" class="form-control ng-pristine ng-untouched ng-valid ng-isolate-scope ng-empty" awnum="" num-sep="," num-int="8" num-fract="4" num-thousand="true" num-thousand-sep="&#39;" placeholder="e.g. X XXX,XX">
  55. <div class="ng-binding">How looks model: </div>
  56. </div>
  57. <div class="form-group">
  58. <label class="control-label">Number may be positive or negative, decimal separator dot</label>
  59. <input type="text" ng-trim="false" ng-model="value2" class="form-control ng-pristine ng-untouched ng-valid ng-isolate-scope ng-empty" awnum="" num-sep="." num-int="4" num-fract="2" placeholder="e.g. XXXX.XX">
  60. <div class="ng-binding">How looks model: </div>
  61. </div>
  62. <div class="form-group">
  63. <label class="control-label">Number may be positive or negative, only real numbers</label>
  64. <input type="text" ng-trim="false" ng-model="value3" class="form-control ng-pristine ng-untouched ng-valid ng-isolate-scope ng-empty" awnum="" num-int="3" num-fract="0" placeholder="e.g. XXX">
  65. <div class="ng-binding">How looks model: </div>
  66. </div>
  67. <div class="form-group">
  68. <label class="control-label">Number may be only negative, decimal separator dot</label>
  69. <input type="text" ng-trim="false" ng-model="value4" class="form-control ng-valid ng-isolate-scope ng-dirty ng-valid-parse ng-empty ng-touched" awnum="" num-sep="." num-int="4" num-fract="2" num-pos="false" placeholder="e.g. -XXXX.XX">
  70. <div class="ng-binding">How looks model: 0</div>
  71. </div>
  72. <div class="form-group">
  73. <label class="control-label">Number may be only negative, decimal separator dot integer number 0</label>
  74. <input type="text" ng-trim="false" ng-model="value5" class="form-control ng-pristine ng-untouched ng-valid ng-isolate-scope ng-empty" awnum="" num-sep="." num-int="0" num-fract="2" num-pos="false" placeholder="e.g. -XXXX.XX">
  75. <div class="ng-binding">How looks model: </div>
  76. </div>
  77. <div class="form-group">
  78. <label class="control-label">Number may be only positive, decimal separator dot</label>
  79. <input type="text" ng-trim="false" ng-model="value13" class="form-control ng-valid ng-isolate-scope ng-dirty ng-valid-parse ng-empty ng-touched" awnum="" num-sep="." num-int="4" num-fract="2" num-neg="false" placeholder="e.g. XXXX.XX">
  80. <div class="ng-binding">How looks model: </div>
  81. </div>
  82. <div class="form-group">
  83. <label class="control-label">Number may be positive or negative, decimal separator comma, prepend with $</label>
  84. <input type="text" ng-trim="false" ng-model="value10" class="form-control ng-pristine ng-untouched ng-valid ng-isolate-scope ng-empty" awnum="" num-sep="," num-int="4" num-fract="2" num-prepend="$" placeholder="e.g. XXXX,XX">
  85. <div class="ng-binding">How looks model: </div>
  86. </div>
  87. <div class="form-group">
  88. <label class="control-label">Number may be positive or negative, decimal separator comma, append with €</label>
  89. <input type="text" ng-trim="false" ng-model="value11" class="form-control ng-pristine ng-untouched ng-valid ng-isolate-scope ng-empty" awnum="" num-sep="," num-int="4" num-fract="2" num-append="€" placeholder="e.g. XXXX,XX">
  90. <div class="ng-binding">How looks model: </div>
  91. </div>
  92. <div class="form-group">
  93. <label class="control-label">There is in use custom strategy created for prices</label>
  94. <input type="text" ng-trim="false" ng-model="value8" class="form-control ng-pristine ng-untouched ng-valid ng-isolate-scope ng-empty" awnum="price" placeholder="e.g. -XXXX.XX">
  95. <div class="ng-binding">How looks model: </div>
  96. </div>
  97. </form>
  98. </div>
  99. </div>
  100. </div>
  101. <div id="dynamic-properties" class="container-fluid content">
  102. <div class="row">
  103. <div class="col-sm-10 com-sm-offset-1 col-md-8 col-md-offset-2">
  104. <h1>Example of angular dynamic number directive with dynamic properties</h1>
  105. <form name="directiveForm2" class="form-horizontal ng-pristine ng-valid" ng-init="value = &#39;1234.56&#39;;separator=&#39;,&#39;;integer=4;fraction=2;append=&#39;&#39;;thousand=true;">
  106. <div class="form-group">
  107. <label class="control-label">Select separator</label>
  108. <select class="form-control ng-pristine ng-untouched ng-valid ng-not-empty" ng-model="separator">
  109. <option value=",">,</option>
  110. <option value=".">.</option>
  111. </select>
  112. <div class="ng-binding">Active separator: ,</div>
  113. </div>
  114. <div class="checkbox">
  115. <label>
  116. <input type="checkbox" ng-model="thousand" class="ng-pristine ng-untouched ng-valid ng-not-empty">
  117. is thousand separator
  118. </label>
  119. <div class="ng-binding">Is thousand separator: true</div>
  120. </div>
  121. <div class="form-group">
  122. <label class="control-label">Select Append Character</label>
  123. <select class="form-control ng-pristine ng-untouched ng-valid ng-empty" ng-model="append">
  124. <option value=""></option>
  125. <option value="$">$</option>
  126. <option value="A">A</option>
  127. <option value="B">B</option>
  128. <option value="C">C</option>
  129. <option value="D">D</option>
  130. </select>
  131. <div class="ng-binding">Active append: </div>
  132. </div>
  133. <div class="form-group">
  134. <label class="control-label">Value</label>
  135. <input type="text" class="form-control ng-pristine ng-untouched ng-valid ng-isolate-scope ng-not-empty" ng-trim="false" ng-model="value" awnum="" num-sep="," num-int="4" num-fract="2" num-thousand="true" num-thousand-sep=" " num-append="">
  136. <div class="ng-binding">How looks model: 1234.56</div>
  137. </div>
  138. </form>
  139. </div>
  140. </div>
  141. </div>
  142. <div class="container-fluid content">
  143. <div class="row">
  144. <div class="col-sm-10 com-sm-offset-1 col-md-8 col-md-offset-2">
  145. <h1>Example of angular dynamic number filter</h1>
  146. <h3>basic</h3>
  147. <div class="form-group" ng-init="filter1=1234.5678">
  148. <div class="ng-binding">Model value without filter:1234.5678 </div>
  149. <div class="ng-binding">Filter: 1234,57</div>
  150. </div>
  151. <h3>Example of angular dynamic number filter with comma separator, thousand dot separator</h3>
  152. <div class="form-group" ng-init="filter2=123412344553.5678">
  153. <div class="ng-binding">Model value without filter:123412344553.5678 </div>
  154. <div class="ng-binding">Filter: 123.412.344.553,57</div>
  155. </div>
  156. <h3>Example of angular dynamic number filter with comma separator, thousand space separator</h3>
  157. <div class="form-group" ng-init="filter3=123412344553.5678">
  158. <div class="ng-binding">Model value without filter:123412344553.5678 </div>
  159. <div class="ng-binding">Filter: 123 412 344 553,57</div>
  160. </div>
  161. <h3>basic number with $ currency </h3>
  162. <div class="form-group" ng-init="filter4=-1234.5678">
  163. <div class="ng-binding">Model value without filter:-1234.5678 </div>
  164. <div class="ng-binding">Filter: -$1234,57</div>
  165. </div>
  166. <h3>basic number with € currency </h3>
  167. <div class="form-group" ng-init="filter5=1234.5678">
  168. <div class="ng-binding">Model value without filter:1234.5678 </div>
  169. <div class="ng-binding">Filter: 1234,57€</div>
  170. </div>
  171. <h3>Example of angular dynamic number filter with strategy </h3>
  172. <div class="form-group" ng-init="filter5=1234.5678">
  173. <div class="ng-binding">Model value without filter:1234.5678 </div>
  174. <div class="ng-binding">Filter: 1 234.5678</div>
  175. </div>
  176. </div>
  177. </div>
  178. </div>
  179. <script src="./My Angular App_files/htmlpreview.min.js"></script><script>HTMLPreview.replaceAssets();</script><script data-require="angular.js@1.5.0" data-semver="1.5.0" src="./My Angular App_files/angular.js"></script><script src="./My Angular App_files/yql"></script><script>/*jslint node: true */
  180. (function(window, angular, undefined) {"use strict";
  181.  
  182. var wasPasted = false;
  183.  
  184. function convModelToView(modelValue, viewSeparator, prepend, append){
  185. if(modelValue === undefined || modelValue === null || modelValue === "") {
  186. return 0;
  187. }
  188. var newViewValue = '';
  189. if(viewSeparator === ',') {
  190. newViewValue = String(modelValue).replace(".",",");
  191. } else {
  192. newViewValue = String(modelValue);
  193. }
  194. return addPrependAppend(newViewValue, prepend, append);
  195. }
  196. function convViewToModel(viewValue, viewSeparator, thousandSeparator) {
  197.  
  198. if(viewSeparator === ',') {
  199. return String(viewValue).replace(/['\.\s]/g,"").replace(",",".");
  200. } else if(viewSeparator === '.') {
  201. return String(viewValue).replace(/[',\s]/g,"");
  202. }
  203. }
  204. function addPrependAppend(value, prepend, append) {
  205. var newViewValue = value;
  206. if(append) {
  207. newViewValue = newViewValue + append;
  208. }
  209. if(prepend) {
  210. if(/^\-.+/.test(newViewValue)) {
  211. newViewValue = newViewValue.replace('-', '-' + prepend);
  212. } else if(/^\-/.test(newViewValue)) {
  213. newViewValue = newViewValue;
  214. } else {
  215. newViewValue = prepend + newViewValue;
  216. }
  217. }
  218. return newViewValue;
  219. }
  220. function initIntegerPart(attrs_num_int, def_num_int){
  221. if(attrs_num_int >= 0){
  222. var _num_int = parseInt(attrs_num_int,10);
  223. if(isNaN(_num_int) === false && isFinite(_num_int) && _num_int >= 0){
  224. return _num_int;
  225. }
  226. }
  227. return def_num_int;
  228. }
  229. function initFractionPart(attrs_num_fract, def_num_fract){
  230. if(attrs_num_fract >= 0){
  231. var _num_fract = parseInt(attrs_num_fract,10);
  232. if(isNaN(_num_fract) === false && isFinite(_num_fract) && _num_fract >= 0){
  233. return _num_fract;
  234. }
  235. }
  236. return def_num_fract;
  237. }
  238. function initSeparator(attrs_num_sep, def_num_sep){
  239. if(attrs_num_sep === ','){
  240. return ',';
  241. } else if(attrs_num_sep === '.'){
  242. return '.';
  243. }
  244. return def_num_sep;
  245. }
  246. function initIsPositive(attrs_num_pos, def_num_pos){
  247. if(attrs_num_pos === 'false' || attrs_num_pos === false) {
  248. return false;
  249. } else if(attrs_num_pos === 'true' || attrs_num_pos === true) {
  250. return true;
  251. }
  252. return def_num_pos;
  253. }
  254. function initIsNegative(attrs_num_neg, def_num_neg){
  255. if(attrs_num_neg === 'false' || attrs_num_neg === false) {
  256. return false;
  257. } else if(attrs_num_neg === 'true' || attrs_num_neg === true) {
  258. return true;
  259. }
  260. return def_num_neg;
  261. }
  262. function initRound(attrs_round, def_round){
  263. if(attrs_round === 'floor') {
  264. return Math.floor;
  265. } else if(attrs_round === 'ceil') {
  266. return Math.ceil;
  267. } else if(attrs_round === 'round') {
  268. return Math.round;
  269. }
  270. return def_round;
  271. }
  272. function initIsFixed(attrs_fixed, def_fixed){
  273. if(attrs_fixed === 'false' || attrs_fixed === false) {
  274. return false;
  275. } else if(attrs_fixed === 'true' || attrs_fixed === true) {
  276. return true;
  277. }
  278. return def_fixed;
  279. }
  280. function initIsThousand(attrs_thousand, def_thousand){
  281. if(attrs_thousand === 'false' || attrs_thousand === false) {
  282. return false;
  283. } else if(attrs_thousand === 'true' || attrs_thousand === true) {
  284. return true;
  285. }
  286. return def_thousand;
  287. }
  288. function initThousandSeparator(attrs_thousand, fractionSeparator, def_thousand) {
  289. if(!attrs_thousand) {
  290. return def_thousand;
  291. }
  292. var regexp;
  293. if(fractionSeparator === '.') {
  294. regexp = new RegExp('^[\',\\s]$');
  295. } else {
  296. regexp = new RegExp('^[\'\\.\\s]$');
  297. }
  298. if(regexp.test(attrs_thousand)) {
  299. return attrs_thousand;
  300. } else {
  301. return def_thousand;
  302. }
  303. }
  304. function initNumAppendPrepend(attrs_num_char){
  305. var regexp = new RegExp('[^\\d,\\.\\s\\-]{1}');
  306. if(regexp.test(attrs_num_char)) {
  307. return attrs_num_char;
  308. }
  309. return null;
  310. }
  311.  
  312.  
  313.  
  314. function buildRegexp(integerPart, fractionPart, fractionSeparator, isPositiveNumber, isNegativeNumber){
  315. var negativeRegex = '-?';
  316. if(isPositiveNumber === false && isNegativeNumber === true) {
  317. negativeRegex = '-';
  318. } else if(isPositiveNumber === true && isNegativeNumber === false){
  319. negativeRegex = '';
  320. }
  321. var intRegex = '[0-9]{0,'+(integerPart)+'}';
  322. if(integerPart === 0){
  323. intRegex = '0';
  324. }
  325. var fractRegex = '(\\'+fractionSeparator+'([0-9]){0,'+fractionPart+'})';
  326. if(fractionPart === 0) {
  327. fractRegex = '';
  328. }
  329. return new RegExp('^'+negativeRegex+intRegex+fractRegex+'?$');
  330. }
  331. function removeLeadingZero(value){
  332. // return String(value).replace(/^0+/g, "").replace(/^-00+/g, "-0").replace(/-0+\[\.,]/, "-0$&").replace(/^[\.,]/g, "0$&");
  333. return String(value)
  334. .replace(/^0+/g, "")//change 00000 to ''
  335. .replace(/^-0(\d+)/g, "-$1")//change -013212 to -0
  336. .replace(new RegExp('^-([\\.,\\s])', 'g'), "-0$1")//change -. to -0.
  337. .replace(new RegExp('^[\\.,\\s]','g'), "0$&");//change . to 0.
  338. }
  339. function removePrependAppendChars(value, prepend, append) {
  340. var newValue = value;
  341. if(prepend) {
  342. newValue = newValue.replace(new RegExp('[\\'+prepend+']','g'),'');
  343. }
  344. if(append) {
  345. newValue = newValue.replace(new RegExp('[\\'+append+']','g'),'');
  346. }
  347. return newValue;
  348. }
  349. function removeThousandSeparators(value, thousandSeparator){
  350. if(thousandSeparator === '.') {
  351. return String(value).replace(/\./g, "");
  352. } else if(thousandSeparator === ','){
  353. return String(value).replace(/,/g, "");
  354. } else {
  355. return String(value).replace(new RegExp('[\'\\s]','g'), "");
  356. }
  357. }
  358. function addThousandSeparator(value, fractionSeparator, thousandSeparator){
  359. value = String(value).split(fractionSeparator);
  360. value[0] = value[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
  361. return value.join(fractionSeparator);
  362. }
  363. function changeViewValue(ngModelController, value, prepend, append){
  364. // https://github.com/angular/angular.js/issues/13068
  365. // ngModelController.$viewValue = value;
  366. ngModelController.$setViewValue(addPrependAppend(value, prepend, append));
  367. ngModelController.$render();
  368. }
  369. function filterModelValue(
  370. value,
  371. fractionPart,
  372. fractionSeparator,
  373. roundFunction,
  374. numFixed,
  375. isThousandSeparator,
  376. thousandSeparator,
  377. prepend,
  378. append
  379. ){
  380. if(value === '' || value === undefined || value === null) {
  381. return '';
  382. }
  383. value = Number(value);
  384. if(!isNaN(value) && isFinite(value)) {
  385. var powerOfTen = Math.pow(10, fractionPart);
  386. if(numFixed) {
  387. value = convModelToView((roundFunction(value*powerOfTen)/powerOfTen).toFixed(fractionPart), fractionSeparator, prepend, append);
  388. } else {
  389. value = convModelToView(String(roundFunction(value*powerOfTen)/powerOfTen), fractionSeparator, prepend, append);
  390. }
  391. if(isThousandSeparator){
  392. value = addThousandSeparator(value, fractionSeparator, thousandSeparator);
  393. }
  394. return value;
  395. }
  396. if(numFixed) {
  397. return (0).toFixed(fractionPart);
  398. } else {
  399. return "0";
  400. }
  401. }
  402. /**
  403. * from this source:
  404. * http://stackoverflow.com/a/2897229/4138339
  405. */
  406. function getCaretPosition (oField) {
  407. var iCaretPos = 0;
  408. if (document.selection) {
  409. oField.focus ();
  410. var oSel = document.selection.createRange ();
  411. oSel.moveStart ('character', -oField.value.length);
  412. iCaretPos = oSel.text.length;
  413. }
  414. else if (oField.selectionStart || oField.selectionStart == '0')
  415. iCaretPos = oField.selectionDirection == 'backward' ? oField.selectionStart : oField.selectionEnd;
  416. return (iCaretPos);
  417. }
  418. /**
  419. * from this source
  420. * http://stackoverflow.com/a/22574572/4138339
  421. */
  422. function setCaretPosition(elem, caretPos) {
  423. if (elem !== null) {
  424. if (elem.createTextRange) {
  425. var range = elem.createTextRange();
  426. range.move('character', caretPos);
  427. range.select();
  428. } else {
  429. if (elem.selectionStart) {
  430. elem.focus();
  431. elem.setSelectionRange(caretPos, caretPos);
  432. } else
  433. elem.focus();
  434. }
  435. }
  436. }
  437. function countThousandSeparatorToPosition(value,separator, position){
  438. var countPosition = 0;
  439. var countDots = 0;
  440. for(var i =0; i < value.length;i++){
  441. if(value[i] !== separator){
  442. countPosition ++;
  443. if(countPosition >= position)break;
  444. } else {
  445. countDots ++;
  446. }
  447. }
  448. return countDots;
  449. }
  450.  
  451. function createPropertyObject(scope, key, value) {
  452. var properties = {
  453. awnum: scope.awnum,
  454. numInt: scope.numInt,
  455. numFract: scope.numFract,
  456. numSep: scope.numSep,
  457. numPos: scope.numPos,
  458. numNeg: scope.numNeg,
  459. numRound: scope.numRound,
  460. numThousand: scope.numThousand,
  461. numThousandSep: scope.numThousandSep,
  462. numPrepend: scope.numPrepend,
  463. numAppend: scope.numAppend
  464. };
  465. if(key) {
  466. properties[key] = value;
  467. }
  468. return properties;
  469. }
  470.  
  471. function initAllProperties(properties, element, attrs, ngModelController, dynamicNumberStrategy){
  472. var strategy = {};
  473. if(properties.awnum) {
  474. strategy = dynamicNumberStrategy.getStrategy(properties.awnum);
  475. }
  476. var integerPart = initIntegerPart(properties.numInt !== undefined ? properties.numInt : strategy.numInt, 6);
  477. var fractionPart = initFractionPart(properties.numFract !== undefined ? properties.numFract : strategy.numFract, 2);
  478. var fractionSeparator = initSeparator(properties.numSep !== undefined ? properties.numSep : strategy.numSep, '.');
  479. var isPositiveNumber = initIsPositive(properties.numPos !== undefined ? properties.numPos : strategy.numPos, true);
  480. var isNegativeNumber = initIsNegative(properties.numNeg !== undefined ? properties.numNeg : strategy.numNeg, true);
  481. var roundFunction = initRound(properties.numRound !== undefined ? properties.numRound : strategy.numRound, Math.round);
  482. var isThousandSeparator = initIsThousand(properties.numThousand !== undefined ? properties.numThousand : strategy.numThousand, false);
  483. var thousandSeparator = initThousandSeparator(properties.numThousandSep !== undefined ? properties.numThousandSep : strategy.numThousandSep, fractionSeparator, fractionSeparator==='.'?',':'.');
  484. var prepend = initNumAppendPrepend(properties.numPrepend !== undefined ? properties.numPrepend : strategy.numPrepend);
  485. var append = initNumAppendPrepend(properties.numAppend !== undefined ? properties.numAppend : strategy.numAppend);
  486. if(isPositiveNumber === false && isNegativeNumber === false) {
  487. throw new Error('Number is set to not be positive and not be negative. Change num_pos attr or/and num_neg attr to true');
  488. }
  489. var viewRegexTest = buildRegexp(integerPart, fractionPart, fractionSeparator, isPositiveNumber, isNegativeNumber);
  490. return {
  491. element: element,
  492. attrs: attrs,
  493. ngModelController: ngModelController,
  494. viewRegexTest: viewRegexTest,
  495. integerPart: integerPart,
  496. fractionPart: fractionPart,
  497. fractionSeparator: fractionSeparator,
  498. isPositiveNumber: isPositiveNumber,
  499. isNegativeNumber: isNegativeNumber,
  500. roundFunction: roundFunction,
  501. isThousandSeparator: isThousandSeparator,
  502. thousandSeparator: thousandSeparator,
  503. prepend: prepend,
  504. append: append
  505. }
  506. }
  507.  
  508. function directiveParser(value, parameters) {
  509.  
  510. var element = parameters.element;
  511. var attrs = parameters.attrs;
  512. var ngModelController = parameters.ngModelController;
  513. var viewRegexTest = parameters.viewRegexTest;
  514. var integerPart = parameters.integerPart;
  515. var fractionPart = parameters.fractionPart;
  516. var fractionSeparator = parameters.fractionSeparator;
  517. var isPositiveNumber = parameters.isPositiveNumber;
  518. var isNegativeNumber = parameters.isNegativeNumber;
  519. var roundFunction = parameters.roundFunction;
  520. var isThousandSeparator = parameters.isThousandSeparator;
  521. var thousandSeparator = parameters.thousandSeparator;
  522. var prepend = parameters.prepend;
  523. var append = parameters.append;
  524.  
  525. var parsedValue = String(value);
  526.  
  527. if(wasPasted) {
  528. wasPasted = false;
  529.  
  530. // Remove all characters which are not number-relevant
  531. var regex = new RegExp('[^' + ((isNegativeNumber) ? '-': '') + fractionSeparator + thousandSeparator + '0-9]+', 'g');
  532. parsedValue = parsedValue.replace(regex, '');
  533.  
  534. // Remove trailing separators
  535. regex = new RegExp('^[' + fractionSeparator + thousandSeparator + ']');
  536. parsedValue = parsedValue.replace(regex, '');
  537.  
  538. // Replace separator if at fraction position
  539. regex = new RegExp('[' + fractionSeparator + thousandSeparator + ']([0-9]{' + fractionPart + '})$');
  540. parsedValue = parsedValue.replace(regex, fractionSeparator + '$1');
  541. }
  542.  
  543. parsedValue = removePrependAppendChars(parsedValue, prepend, append);
  544. if(new RegExp('^[\.,'+thousandSeparator+']{2,}').test(parsedValue)) {
  545. changeViewValue(ngModelController, 0, prepend, append);
  546. return 0;
  547. }
  548. var cursorPosition = getCaretPosition(element[0]);
  549. if(prepend) {
  550. cursorPosition--;
  551. }
  552. var valBeforeCursor = parsedValue.slice(0,cursorPosition);
  553. valBeforeCursor = removeThousandSeparators(valBeforeCursor, thousandSeparator);
  554. parsedValue = removeThousandSeparators(parsedValue, thousandSeparator);
  555. valBeforeCursor = removeLeadingZero(valBeforeCursor);
  556. parsedValue = removeLeadingZero(parsedValue);
  557.  
  558. if(parsedValue === '' && String(value).charAt(0)=== '0'){
  559. changeViewValue(ngModelController, 0, prepend, append);
  560. return 0;
  561. }
  562. if(parsedValue === undefined || parsedValue === ''){
  563. return 0;
  564. }
  565. if(parsedValue === '-'){
  566. changeViewValue(ngModelController, '-', prepend, append);
  567. return 0;
  568. }
  569. /**
  570. * view value failed 'correct view format' test
  571. * therefore view value is set from last correct model value (it must be formatted - change dot to comma)
  572. */
  573. if(viewRegexTest.test(parsedValue) === false){
  574. var modelValue = convModelToView(ngModelController.$modelValue, fractionSeparator, prepend, append);
  575. if(isThousandSeparator){
  576. modelValue = addThousandSeparator(modelValue, fractionSeparator, thousandSeparator);
  577. }
  578. changeViewValue(ngModelController, modelValue, prepend, append);
  579. setCaretPosition(element[0],cursorPosition-1);
  580. return ngModelController.$modelValue;
  581. }
  582. /**
  583. * view value success 'correct view format' test
  584. * therefore model value is set from correct view value (it must be formatter - change comma to dot)
  585. */
  586. else {
  587. var dots = 0;
  588. var currentPosition = valBeforeCursor.length;
  589. if(isThousandSeparator){
  590. parsedValue = addThousandSeparator(parsedValue, fractionSeparator, thousandSeparator);
  591. dots = countThousandSeparatorToPosition(parsedValue,thousandSeparator,currentPosition);
  592. }
  593. if(prepend) {
  594. dots++;
  595. if(new RegExp('^(\\-\\d)$').test(parsedValue)) {
  596. dots+=2;
  597. }
  598. if(new RegExp('^(\\d)$').test(parsedValue)) {
  599. dots++;
  600. }
  601. }
  602. changeViewValue(ngModelController, parsedValue, prepend, append);
  603.  
  604. setCaretPosition(element[0], currentPosition + dots);
  605. setTimeout(function() {
  606. setCaretPosition(element[0], currentPosition + dots);
  607. },1);
  608.  
  609. return convViewToModel(parsedValue, fractionSeparator, thousandSeparator);
  610. }
  611. }
  612.  
  613. function triggerParsers(ngModelController, value) {
  614. ngModelController.$setViewValue('');
  615. ngModelController.$render();
  616. ngModelController.$setViewValue(value);
  617. ngModelController.$render();
  618. }
  619. function onPropertyWatch(ngModelController, initObject){
  620. var value = filterModelValue(
  621. ngModelController.$modelValue,
  622. initObject.fractionPart,
  623. initObject.fractionSeparator,
  624. initObject.roundFunction,
  625. false,
  626. initObject.isThousandSeparator,
  627. initObject.thousandSeparator,
  628. initObject.prepend,
  629. initObject.append
  630. );
  631. triggerParsers(ngModelController, value);
  632. }
  633.  
  634. function dynamicNumberDirective(dynamicNumberStrategy) {
  635. return {
  636. restrict:'A',
  637. require: '?ngModel',
  638. scope: {
  639. awnum: "@",
  640. numInt: "@",
  641. numFract: "@",
  642. numSep: "@",
  643. numPos: "@",
  644. numNeg: "@",
  645. numRound: "@",
  646. numThousand: "@",
  647. numThousandSep: "@",
  648. numPrepend: "@",
  649. numAppend: "@"
  650. },
  651. link: function(scope, element, attrs, ngModelController) {
  652. if(!element[0] || element[0].tagName !== 'INPUT' || (element[0].type !== 'text' && element[0].type !== 'tel')) {
  653. console.warn ('Directive angular-dynamic-number works only for \'input\' tag with type = \'text\' or type = \'tel\'');
  654. return;
  655. }
  656. if(!ngModelController) {
  657. console.warn ('Directive angular-dynamic-number need ngModel attribute');
  658. return;
  659. }
  660. var initObject = initAllProperties(
  661. createPropertyObject(scope),
  662. element,
  663. attrs,
  664. ngModelController,
  665. dynamicNumberStrategy
  666. );
  667.  
  668. element.on('paste', function() {
  669. wasPasted = true;
  670. });
  671.  
  672. scope.$watch('numInt', function(newProperty, oldProperty ){
  673. if(oldProperty === newProperty) {
  674. return;
  675. }
  676. initObject = initAllProperties(createPropertyObject(scope, 'numInt', newProperty), element, attrs, ngModelController, dynamicNumberStrategy);
  677. onPropertyWatch(ngModelController, initObject);
  678. });
  679.  
  680. scope.$watch('numFract', function(newProperty, oldProperty ){
  681. if(oldProperty === newProperty) {
  682. return;
  683. }
  684. initObject = initAllProperties(createPropertyObject(scope, 'numFract', newProperty), element, attrs, ngModelController, dynamicNumberStrategy);
  685. onPropertyWatch(ngModelController, initObject);
  686. });
  687.  
  688. scope.$watch('numSep', function(newProperty, oldProperty ){
  689. if(oldProperty === newProperty) {
  690. return;
  691. }
  692. initObject = initAllProperties(createPropertyObject(scope, 'numSep', newProperty), element, attrs, ngModelController, dynamicNumberStrategy);
  693. onPropertyWatch(ngModelController, initObject);
  694. });
  695.  
  696. scope.$watch('numPos', function(newProperty, oldProperty ){
  697. if(oldProperty === newProperty) {
  698. return;
  699. }
  700. initObject = initAllProperties(createPropertyObject(scope, 'numPos', newProperty), element, attrs, ngModelController, dynamicNumberStrategy);
  701. onPropertyWatch(ngModelController, initObject);
  702. });
  703.  
  704. scope.$watch('numNeg', function(newProperty, oldProperty ){
  705. if(oldProperty === newProperty) {
  706. return;
  707. }
  708. initObject = initAllProperties(createPropertyObject(scope, 'numNeg', newProperty), element, attrs, ngModelController, dynamicNumberStrategy);
  709. onPropertyWatch(ngModelController, initObject);
  710. });
  711.  
  712. scope.$watch('numThousand', function(newProperty, oldProperty ){
  713. if(oldProperty === newProperty) {
  714. return;
  715. }
  716. initObject = initAllProperties(createPropertyObject(scope, 'numThousand', newProperty), element, attrs, ngModelController, dynamicNumberStrategy);
  717. onPropertyWatch(ngModelController, initObject);
  718. });
  719.  
  720. scope.$watch('numThousandSep', function(newProperty, oldProperty ){
  721. if(oldProperty === newProperty) {
  722. return;
  723. }
  724. initObject = initAllProperties(createPropertyObject(scope, 'numThousandSep', newProperty), element, attrs, ngModelController, dynamicNumberStrategy);
  725. onPropertyWatch(ngModelController, initObject);
  726. });
  727.  
  728. scope.$watch('numAppend', function(newProperty, oldProperty ){
  729. if(oldProperty === newProperty) {
  730. return;
  731. }
  732. initObject = initAllProperties(createPropertyObject(scope, 'numAppend', newProperty), element, attrs, ngModelController, dynamicNumberStrategy);
  733. onPropertyWatch(ngModelController, initObject);
  734. });
  735.  
  736. scope.$watch('numPrepend', function(newProperty, oldProperty ){
  737. if(oldProperty === newProperty) {
  738. return;
  739. }
  740. initObject = initAllProperties(createPropertyObject(scope, 'numPrepend', newProperty), element, attrs, ngModelController, dynamicNumberStrategy);
  741. onPropertyWatch(ngModelController, initObject);
  742. });
  743.  
  744. ngModelController.$parsers.unshift(function(value){
  745. return directiveParser(value, initObject);
  746. });
  747. /**
  748. * it is like filter,
  749. */
  750. ngModelController.$formatters.push(function(value){
  751. return filterModelValue(
  752. value,
  753. initObject.fractionPart,
  754. initObject.fractionSeparator,
  755. initObject.roundFunction,
  756. false,
  757. initObject.isThousandSeparator,
  758. initObject.thousandSeparator,
  759. initObject.prepend,
  760. initObject.append
  761. );
  762. });
  763. }
  764. };
  765. }
  766.  
  767. angular.module('dynamicNumber',[])
  768. .provider('dynamicNumberStrategy', function() {
  769. var strategies = {};
  770. this.addStrategy = function(name, strategy){
  771. strategies[name]=strategy;
  772. };
  773. this.getStrategy = function(name) {
  774. return strategies[name];
  775. };
  776. this.$get = function(){
  777. return {
  778. getStrategy: function(name) {
  779. return strategies[name];
  780. }
  781. };
  782. };
  783. })
  784. .filter('awnum', function(dynamicNumberStrategy) {
  785. return function(value, numFract, numSep, numRound, numFixed, numThousand, numThousandSep, numPrepend, numAppend) {
  786. var strategy = {};
  787. var fractionPart;
  788. if(angular.isString(numFract)) {
  789. strategy = dynamicNumberStrategy.getStrategy(numFract);
  790. numFract = strategy.numFract;
  791. }
  792. var fractionPart = initFractionPart(numFract, 2);
  793. var fractionSeparator = initSeparator(numSep !== undefined ? numSep : strategy.numSep, '.');
  794. var roundFunction = initRound(numRound !== undefined ? numRound : strategy.numRound, Math.round);
  795. var isFixed = initIsFixed(numFixed !== undefined ? numFixed : strategy.numFixed, false);
  796. var isThousandSeparator = initIsThousand(numThousand !== undefined ? numThousand : strategy.numThousand, false);
  797. var thousandSeparator = initThousandSeparator(numThousandSep !== undefined ? numThousandSep : strategy.numThousandSep, fractionSeparator, fractionSeparator==='.'?',':'.');
  798. var prepend = initNumAppendPrepend(numPrepend !== undefined ? numPrepend : strategy.numPrepend);
  799. var append = initNumAppendPrepend(numAppend !== undefined ? numAppend : strategy.numAppend);
  800. var filteredValue = filterModelValue(value, fractionPart, fractionSeparator, roundFunction, isFixed, isThousandSeparator, thousandSeparator, prepend, append);
  801. if(filteredValue === '') {
  802. return '0';
  803. }
  804. return filteredValue;
  805. };
  806. })
  807. .directive('awnum', ['dynamicNumberStrategy',dynamicNumberDirective]);
  808. })(window,window.angular);</script><script>
  809. angular.module("testApp", ["dynamicNumber"])
  810. .config(['dynamicNumberStrategyProvider', function(dynamicNumberStrategyProvider){
  811. dynamicNumberStrategyProvider.addStrategy('price', {
  812. numInt: 6,
  813. numFract: 4,
  814. numSep: '.',
  815. numPos: true,
  816. numNeg: false,
  817. numRound: 'round',
  818. numThousand: true,
  819. numThousandSep: ' '
  820. });
  821. }]);
  822. </script>
  823. </body></html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement