Angular的数字文本框

时间:2014-06-04 14:28:30

标签: angularjs

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

我知道他们有角度指令翻译,但我想避免那么重。

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

有没有人遇到类似这样的事情或者有关如何以角度方式进行此操作的建议?

1 个答案:

答案 0 :(得分:2)

在@ 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格式,但在使用角度原生过滤器时保留了客户端格式化的原始值:)