programing

angularJ의 숫자에 1000개의 구분 쉼표를 추가하는 방법은 무엇입니까?

codeshow 2023. 3. 23. 22:57
반응형

angularJ의 숫자에 1000개의 구분 쉼표를 추가하는 방법은 무엇입니까?

숫자 문자열을 1,000개의 쉼표를 사용하여 표시할 숫자로 변환하기만 하면 됩니다.

var value = "123456";

"123,465"를 그리드로 표시하고 싶습니다.저는 이것에 대해 몇 가지 문서를 찾아봤지만, HTML로 표시하는 것이 전부입니다.이것을 동적 그리드로 표시하고 싶습니다.

function numberRenderer (params) {
                    return new Number (params.value);
                }

숫자를 표시용 문자열로 변환할 수 있도록 포맷하고 싶습니다.

필터 사용...

HTML 사용법

{{ number_expression | number : fractionSize}}

Js 사용법

$filter('number')(number, fractionSize)

@jbrown의 답변은 감사했습니다만, 유저가 숫자를 입력할 때 입력란에 콤마를 추가하는 솔루션을 찾고 있었습니다.결국 이 지령을 찾았는데 그게 바로 내가 필요로 하는 것이었음이 증명되었다.

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;
      }
    }
  };
});

AngularJS Directive는 다음에서 찾을 수 있습니다.각진JS 번호 입력 형식 보기

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

Anguna가 올린 글에 매우 감사합니다.제가 유일하게 놓쳤던 것은 화폐처럼 소수점 이하를 처리하는 것이었습니다.표시된 값에 소수점 2자리를 자동으로 추가해 주길 바랐습니다.단, 이 문제는 최초 표시 시에만 발생하며 필드를 나갈 때 다시 발생해야 합니다.저는 그 시나리오에 대응하기 위해 코드를 업데이트했습니다.

var app = angular.module("myApp", []);

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

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

            // 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());
            });

            elem.bind('blur', function () {
                // Add Decimal places if they do not exist
                var valStr = elem.val().toString();

                valStr = setDecimal(valStr);

                elem.val(valStr);
            });

            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;
            }
            function setDecimal(val) {
                // Add Decimal places if they do not exist
                var valStr = val.toString();

                // If no decimal then add it
                if (valStr.indexOf('.') === -1) {
                    valStr += '.00';
                }
                else {
                    var decimalDigits = valStr.length - (valStr.indexOf('.') + 1);
                    var missingZeros = 2 - decimalDigits;
                    for (var i = 1; i <= missingZeros; i++) {
                        valStr += '0';
                    }
                }

                return valStr;
            }

        }
    };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>

<div ng-app="myApp">
  <input type="text" ng-model="myModelValue" currency-input />
</div>

언급URL : https://stackoverflow.com/questions/36091421/how-to-add-thousand-separating-commas-for-numbers-in-angularjs

반응형