【问题标题】:Numeric Textbox for AngularAngular 的数字文本框
【发布时间】:2014-06-04 14:28:30
【问题描述】:

我正在寻找一个指令,它允许我执行 Kendo-UI 的数字文本框控件 (http://demos.telerik.com/kendo-ui/numerictextbox/index) 之类的操作。

我知道他们有角度指令翻译器,但我想避免它的重量。

基本上:小数、货币、逗号、数字仅在实际文本框中。我知道 angular 有过滤器,但我似乎无法在文本框中找到它们实际工作。

有没有人遇到过这样的事情或有关于如何在 Angular 中做到这一点的建议?

【问题讨论】:

标签: angularjs


【解决方案1】:

基于@1st4ck 的建议,我实现了自己的指令,该指令使用角度核心过滤器,但将它们显示为文本框:)

指令

var module = angular.module('components.number', []);

module.directive('numberInput', function ($timeout, $filter) {
    return {
        restrict: 'EA',
        templateUrl: "common/components/number/number.tpl.html",
        scope:{
            ngModel: "=",
            format: "=",
            min: "=",
            max: "=",
            step: "=",
            decimalPlaces: "=decimals"
        },
        link: function($scope, $elm, $attrs) {
            $scope.showNumber = false;
            $scope.numberBlurred = function(){
                $scope.showNumber = false;
            };

            $scope.textBlurred = function(){
                $scope.showNumber = true;
            };

            $scope.textFocused = function(){
                $scope.showNumber = true;
                $timeout(function(){
                    $elm.find('input[type=number]').focus();
                }, 50)
            };

            $scope.$watch('ngModel', function(){
                var formatted;

                if($attrs.format === "percent"){
                    formatted = $filter("number")($scope.ngModel, 0);
                    if(formatted){
                        formatted = formatted + "%";
                    }
                } else if($attrs.format === "decimal"){
                    formatted = $filter("number")($scope.ngModel, $attrs.decimalPlaces || 2);
                } else {
                    formatted = $filter($attrs.format)($scope.ngModel);
                }

                $scope.formatted = formatted;
            }, true);

        }
    };
});

return module;

模板(common/components/number/number.tpl.html)

<input type="number"
       ng-model="ngModel"
       class="form-control"
       ng-show="showNumber"
       ng-blur="numberBlurred()" />

<input value="{{formatted}}"
       class="form-control"
       ng-click="textFocused()"
       ng-hide="showNumber" />

用法

<number-input ng-model="myModel" format="currency">
<number-input ng-model="myModel" format="decimal" decimals="5">
<number-input ng-model="myModel" format="number"> // mainly for thousands

对焦的超时使用有点奇怪,但很好。做的工作!

此解决方案的优点在于,它向用户显示了格式化的 UI,但在使用 Angular 本机过滤器时保留了用于在客户端格式化的原始值 :)

【讨论】:

  • 感谢分享@amcdnl!看起来不错,但我对实施过程有点迷茫。你能举一个你的解决方案的例子吗?
猜你喜欢
  • 1970-01-01
  • 2016-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-27
  • 1970-01-01
  • 2021-09-07
  • 1970-01-01
相关资源
最近更新 更多