负值不应显示在文本框中

时间:2018-02-05 08:04:54

标签: javascript html angularjs

Plunker

我有一个文本字段,我不想在文本框中显示负值。如果值为负,那么我只是留下该文本框。

我有一个指令,它不允许负值但是当数据来自后端时它显示负值。

app.directive('numbersOnly', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attr, ngModelCtrl) {
            function fromUser(text) {
                if (text) {
                    var transformedInput = text.replace(/[^0-9]/g, '');

                    if (transformedInput !== text) {
                        ngModelCtrl.$setViewValue(transformedInput);
                        ngModelCtrl.$render();
                    }
                    return transformedInput;
                }
                return undefined;
            }            
            ngModelCtrl.$parsers.push(fromUser);
        }
    };
});

2 个答案:

答案 0 :(得分:0)

使用Math.abs(x)

function LoginController($scope) {
    $scope.number = Math.abs(-10);
      $scope.number1 =  Math.abs(-20);
        $scope.number2 =  Math.abs(-30);
}

Ref Link

答案 1 :(得分:0)

这是否符合您的要求?

https://jsfiddle.net/kjtqLvch/

HTML:

<div ng-app ng-controller="LoginController">
<input ng-model="number" ng-change="validate()" type="number" ng-init="validate()"></input>

    <input ng-model="number1"></input>
    <input ng-model="number2"></input>
    <input type="submit" ng-click="login()" value="Login"></input>
</div>

JS:

function LoginController($scope) {
    $scope.number = -10;
      $scope.number1 = -20;
        $scope.number2 = -30;
        $scope.validate = function(){
            $scope.number>=0?
          $scope.number = $scope.number:
          $scope.number=0;
        }
}