angularjs – $parsers不使用space

前端之家收集整理的这篇文章主要介绍了angularjs – $parsers不使用space前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个服装指令来设置%的东西,例如:
– 快乐:[90]
– 悲伤:[10]

所以它只允许1到100.所以我不想允许任何字符等.我知道我可以使用ng-pattern等..但我不希望他们甚至添加一个字符所以我必须这样做.

它的工作原理,但我遇到的问题是空间不会触发$解析器,是否有一个解决方法用于触发空间?

  1. app.directive('numericOnly',function(){
  2. return {
  3. require: 'ngModel',link: function(scope,element,attrs,modelCtrl) {
  4. modelCtrl.$parsers.push(function (inputValue) {
  5.  
  6. //Remove all non numeric values
  7. var transformedInput = inputValue.replace(/\D/g,'');
  8.  
  9. //Remove all spaces
  10. transformedInput = transformedInput.replace(/\s/g,"");
  11.  
  12. //Remove any leading zero
  13. if(transformedInput.substring(0,1) === '0') {
  14. console.log('is zero');
  15. if(transformedInput.length === 1) {
  16. transformedInput = '';
  17. } else {
  18. transformedInput = transformedInput.substring(1,transformedInput.length);
  19. }
  20. }
  21.  
  22. //Make sure it is not over 100
  23. var numberCopy = parseInt(transformedInput);
  24. if(!isNaN(numberCopy)){
  25. if(numberCopy > 100) {
  26. console.log('bigger than 100');
  27. numberCopy = 100;
  28. transformedInput = String(numberCopy);
  29. }
  30. }
  31.  
  32. //If changes done,then update modelCtrl
  33. if (transformedInput!=inputValue) {
  34. modelCtrl.$setViewValue(transformedInput);
  35. modelCtrl.$render();
  36. }
  37.  
  38. //Return
  39. return transformedInput;
  40. });
  41. }
  42. };
  43. });

Plunker:http://plnkr.co/edit/oKXExZ8lkHzUSqHKpm1n?p=preview

默认情况下,Angular会修剪ngModel值.因此,您需要将 ng-trim指令添加到输入元素,它不允许字符串两侧的空格.
  1. <input type="text" numeric-only="" ng-trim="false" ng-model="nyNumber"/>

而且你不再需要这条线了

  1. //Remove all spaces
  2. transformedInput = transformedInput.replace(/\s/g,"");

猜你在找的Angularjs相关文章