PAVITRA
PAVITRA

Reputation: 861

Angular Number only input restrict 0

I'm using Angular and I have a number only input,

Questions is I need to restrict 0. Any suggestions please..

Upvotes: 2

Views: 3067

Answers (2)

Jai
Jai

Reputation: 74738

Add an min='1' attribute:

<input type='number' min='1'>

But i guess you just need to restrict 0 only, so all other numbers positives and negatives would be insertable, so you can make a function and you can use $event of angular and get the keyCode/stringvalue and that can be restricted like:

var app = angular.module('testapp', []);

app.controller('appCtrl', ['$scope', function($scope) {
    $scope.noZero = function(e) {
      var kc = e.keyCode || e.which;
      if (String.fromCharCode(e.which) == '0' && e.target.value.indexOf('0') == 0) {
        return e.target.value = e.target.value.slice(0, -1);
      }
    };
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
<div ng-app='testapp' ng-controller='appCtrl'>
  <input type='number' ng-keyup='noZero($event)'>
</div>

Upvotes: 0

Vivek
Vivek

Reputation: 13298

With the use of $parsers provided by NgModelController, we can scan and remove zero from the number field.

I have created a directive which will restrict zero in the number field. Add it in your application.

Then you can use it on number input element to prevent the zero. It will still allow negative numbers.

Note : You need to use it as an attribute on input field. like restrict-zero

Example : <input type="number" restrict-zero ng-model="number">

See Plnkr

angular.module('app', [])
  .controller('myCtrl', function($scope) {
    $scope.number = '';
  })
  .directive('restrictZero', function() {
    return {
      require: 'ngModel',
      restrict: 'A',
      link: function(scope, element, attrs, modelCtrl) {
        modelCtrl.$parsers.push(function(inputValue) {
          if (inputValue == null)
            return ''
          cleanInputValue = inputValue.replace(/^0/g, '');
          if (cleanInputValue != inputValue) {
            modelCtrl.$setViewValue(cleanInputValue);
            modelCtrl.$render();
          }
          return cleanInputValue;
        });
      }
    }
  });
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
  <body ng-app="app" ng-controller="myCtrl">
    Number : <input type="number" restrict-zero ng-model="number" name="number">
  </body>

</html>

Upvotes: 1

Related Questions