programing

AngularJS 번호 입력 형식 보기

lovejava 2023. 3. 20. 21:13

AngularJS 번호 입력 형식 보기

사용자가 큰 숫자를 입력할 때 형식화된 숫자 입력을 사용하여 수천 개의 구분자를 표시합니다.다음은 제가 사용한 디렉티브 코드입니다.http://jsfiddle.net/LCZfd/3/

사용할 때input type="text"작동하지만, 제가 사용하고 싶을 때input type="number"사용자가 큰 숫자를 입력할 때 뭔가에 의해 이상하게 청소됩니다.

의 문제점은 무엇입니까?input[number]?

댓글에 써있는 것처럼input type="number"숫자만 지원합니다. 소수 구분 기호(일반적으로),또는.로케일에 따라 다름) 및-또는e. 원하는 대로 입력할 수 있지만 브라우저는 알 수 없거나 잘못된 문자를 삭제합니다.

그러면 다음 두 가지 옵션이 있습니다.

  • 사용하다type="text"패턴 검증은 다음과 같습니다.pattern="[0-9]+([\.,][0-9]+)*"사용자가 입력할 수 있는 값을 제한하고 예시와 같이 값의 형식을 자동으로 지정합니다.
  • 원하는 대로 숫자를 렌더링하고 사용자가 커스텀을 사용할 수 있도록 하는 오버레이를 입력 필드 위에 배치합니다.type="number"입력 제어 기능을 제공합니다(여기서 설명하겠습니다.

후자의 솔루션에서는 추가 기능을 사용합니다.<label>태그는 현재 값을 포함하며 입력 필드에 포커스를 맞추면 CSS에 의해 숨겨집니다.

몇 년이 지난 지금도 HTML5 솔루션을 바로 사용할 수 있는 것은 아닙니다.

사용하고 있다<input type="tel">또는<input type="text">("tel"은 Android 및 iOS에서 숫자 키보드를 불러옵니다. 경우에 따라서는 이것이 보너스입니다.

그리고 나서 지시사항이 필요했죠:

  • 비문자를 걸러내다
  • 사용자 유형으로 1000자 쉼표를 추가합니다.
  • 사용하다$parsers그리고.keyup세팅하다elem.val()그리고.$formatters디스플레이를 설정하려면...
  • ...뒤에서 임무를 부여하다ng-model부동 소수점 수

다음 지시 예제에서는 양수 또는 정수만 지정하는 경우를 제외하고 음수 및 부동 소수점 숫자를 사용할 수 있습니다.

제가 원하는 완전한 솔루션은 아니지만, 그 차이를 메워줄 수 있을 것 같습니다.

HTML

<input type="text" ng-model="someNumber" number-input />

자바스크립트

myApp.directive('numberInput', function($filter) {
  return {
    require: 'ngModel',
    link: function(scope, elem, attrs, ngModelCtrl) {

      ngModelCtrl.$formatters.push(function(modelValue) {
        return setDisplayNumber(modelValue, true);
      });

      // it's best to change the displayed text using elem.val() rather than
      // ngModelCtrl.$setViewValue because the latter will re-trigger the parser
      // and not necessarily in the correct order with the changed value last.
      // see http://radify.io/blog/understanding-ngmodelcontroller-by-example-part-1/
      // for an explanation of how ngModelCtrl works.
      ngModelCtrl.$parsers.push(function(viewValue) {
        setDisplayNumber(viewValue);
        return setModelNumber(viewValue);
      });

      // occasionally the parser chain doesn't run (when the user repeatedly 
      // types the same non-numeric character)
      // for these cases, clean up again half a second later using "keyup"
      // (the parser runs much sooner than keyup, so it's better UX to also do it within parser
      // to give the feeling that the comma is added as they type)
      elem.bind('keyup focus', function() {
        setDisplayNumber(elem.val());
      });
      function setDisplayNumber(val, formatter) {
        var valStr, displayValue;

        if (typeof val === 'undefined') {
          return 0;
        }

        valStr = val.toString();
        displayValue = valStr.replace(/,/g, '').replace(/[A-Za-z]/g, '');
        displayValue = parseFloat(displayValue);
        displayValue = (!isNaN(displayValue)) ? displayValue.toString() : '';

        // handle leading character -/0
        if (valStr.length === 1 && valStr[0] === '-') {
          displayValue = valStr[0];
        } else if (valStr.length === 1 && valStr[0] === '0') {
          displayValue = '';
        } else {
          displayValue = $filter('number')(displayValue);
        }
        // handle decimal
        if (!attrs.integer) {
          if (displayValue.indexOf('.') === -1) {
            if (valStr.slice(-1) === '.') {
              displayValue += '.';
            } else if (valStr.slice(-2) === '.0') {
              displayValue += '.0';
            } else if (valStr.slice(-3) === '.00') {
              displayValue += '.00';
            }
          } // handle last character 0 after decimal and another number
          else {
            if (valStr.slice(-1) === '0') {
              displayValue += '0';
            }
          }
        }

        if (attrs.positive && displayValue[0] === '-') {
          displayValue = displayValue.substring(1);
        }

        if (typeof formatter !== 'undefined') {
          return (displayValue === '') ? 0 : displayValue;
        } else {
          elem.val((displayValue === '0') ? '' : displayValue);
        }
      }
      function setModelNumber(val) {
        var modelNum = val.toString().replace(/,/g, '').replace(/[A-Za-z]/g, '');
        modelNum = parseFloat(modelNum);
        modelNum = (!isNaN(modelNum)) ? modelNum : 0;
        if (modelNum.toString().indexOf('.') !== -1) {
          modelNum = Math.round((modelNum + 0.00001) * 100) / 100;
        }
        if (attrs.positive) {
          modelNum = Math.abs(modelNum);
        }
        return modelNum;
      }
    }
  };
});

https://jsfiddle.net/benlk/4dto9738/

를 추가해야 합니다.step귀속number입력.

<input type="number" step="0.01" />

이렇게 하면 부동 소수점이 허용됩니다.

http://jsfiddle.net/LCZfd/1/

또한 다음 버그 스레드를 검토할 것을 권장합니다.number입력이 필요합니다.이 입력 타입은 이번 FF 릴리즈에서 최종적으로 지원되기 때문에 사용하지 않는 것이 좋습니다.

값을 할 수 .,type=number숫자만 사용합니다.콤마를 추가하면 문자열이 됩니다.

http://jsfiddle.net/LCZfd/5 를 참조해 주세요.

콤마를 원한다면 직접 컨트롤을 만드는 것이 좋습니다.True 값(숫자)과 표시 값(문자열)을 가진 것.

이거 한번 해봐, 내가 본 지시사항을 수정했어...숫자만 입력하도록 제한하려면 어떻게 해야 합니까?

제가 수정한 지시입니다이 지시어는 키업 이벤트를 사용하여 입력을 즉시 수정합니다.

.directive('numericOnly', function($filter) {
 return {
  require: 'ngModel',
  link: function(scope, element, attrs, modelCtrl) {

       element.bind('keyup', function (inputValue, e) {
         var strinput = modelCtrl.$$rawModelValue;
         //filter user input
         var transformedInput = strinput ? strinput.replace(/[^,\d.-]/g,'') : null;
         //remove trailing 0
         if(transformedInput.charAt(0) <= '0'){
           transformedInput = null;
           modelCtrl.$setViewValue(transformedInput);
           modelCtrl.$render();
         }else{
           var decimalSplit = transformedInput.split(".")
           var intPart = decimalSplit[0];
           var decPart = decimalSplit[1];
           //remove previously formated number
           intPart = intPart.replace(/,/g, "");
           //split whole number into array of 3 digits
           if(intPart.length > 3){
             var intDiv = Math.floor(intPart.length / 3);
             var strfraction = [];
             var i = intDiv,
                 j = 3;

             while(intDiv > 0){
               strfraction[intDiv] = intPart.slice(intPart.length-j,intPart.length - (j - 3));
               j=j+3;
               intDiv--;
             }
             var k = j-3;
             if((intPart.length-k) > 0){
               strfraction[0] = intPart.slice(0,intPart.length-k);
             }
           }
           //join arrays
           if(strfraction == undefined){ return;}
             var currencyformat = strfraction.join(',');
             //check for leading comma
             if(currencyformat.charAt(0)==','){
               currencyformat = currencyformat.slice(1);
             }

             if(decPart ==  undefined){
               modelCtrl.$setViewValue(currencyformat);
               modelCtrl.$render();
               return;
             }else{
               currencyformat = currencyformat + "." + decPart.slice(0,2);
               modelCtrl.$setViewValue(currencyformat);
               modelCtrl.$render();
             }
         }
        });
  }

};

이렇게 쓰면...

<input type="text" ng-model="amountallocated" id="amountallocated" numeric-only />

언급URL : https://stackoverflow.com/questions/24001895/angularjs-number-input-formatted-view