2表示angularjs中的可循环数字文本框

时间:2017-02-02 09:26:54

标签: javascript html angularjs textbox

我想要实现的行为是一个数字文本框,在未聚焦时显示2个小数位,在聚焦时显示每个小数位。这与this question中的行为相同:



ko.extenders.digitInput = function(target, option) {
  var realValue = target,
      showRealValue = ko.observable(false),
      displayValue = ko.computed({
        read: function() {
          return showRealValue() 
            ? realValue()
            : parseFloat(realValue()).toFixed(2);
        },
        write: realValue
      }, this);
  
  displayValue.showRealValue = showRealValue;
  
  return displayValue;
};


var ViewModel = function() {
  this.value1 = ko.observable(6.452345).extend({ digitInput: true });
  this.value2 = ko.observable(4.145).extend({ digitInput: true });
};


ko.applyBindings(new ViewModel());

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<input data-bind="value: value1, hasFocus: value1.showRealValue" type="number"/>
<input data-bind="value: value2, hasFocus: value2.showRealValue" type="number"/>
&#13;
&#13;
&#13;

但现在我想使用AngularJS代替Knockoutjs。我对这个框架很陌生,所以我不知道这样做的正确方法是使用服务,工厂还是仅使用ng-blurng-focus在主控制器上调用通用事件。我也在使用Typescript。提前谢谢。

1 个答案:

答案 0 :(得分:0)

我找到了一个有效的解决方案在Typescript中:

interface INumericTextBox extends angular.IDirective {
}

interface INumericTextBoxScope extends angular.IScope {
}

interface INumericTextBoxAttributes extends angular.IAttributes {
    ngModel: string
}

interface IElement extends angular.IAugmentedJQuery {
    value: string
}

NumericTextBox.$inject = ["$window"];
function NumericTextBox($window: angular.IWindowService): INumericTextBox {
    // Usage:
    //     <numeric-textbox></numeric-textbox>
    // Creates:
    // 

    return {
        restrict: "A",
        link: link
    }

    function link(scope: INumericTextBoxScope, element, attrs: INumericTextBoxAttributes, ngModelController) {
        var realValue;
        element.bind('focus', function (scope) {

            if (realValue != null) this.value = realValue;
        })

        element.bind('blur', function (scope) {

            realValue = this.value;
            this.value = parseFloat(this.value).toFixed(2);
        })

        ngModelController.$formatters.push(function (data: number) {
            //convert data from model format to view format
            if (data != null) {
                realValue = data;
                data = parseFloat(data.toFixed(2));
            }
            return data; //converted
        });
    }
}

angular.module("app").directive("numericTextbox", NumericTextBox);

在此处运行javascript示例:plnkr