2

Clear number input type does not work for 'e' number

When I clear the input field with input eee in number type, it does not get cleared. Any other input numbers get cleared. Check the JSFiddle. Any hints would be appreciated.

http://jsfiddle.net/2ankx9up/

<div ng-app="app">
   <div ng-controller="MainCtrl">
    <input type="number" class="form-control" data-ng-model="searchAll"> 
    </input> 
    <a class="clear" href="" data-ng-click="clearSearch()">X</a>
   </div>
</div>
var app = angular.module("app", []);
 app.controller("MainCtrl", function ($scope) {
    $scope.searchAll = "";
    $scope.clearSearch = function () {
       $scope.searchAll = "";
    };
});
2
  • Why are you allowing non-numeric values to be stored against searchAll? The documentation for input[number] states that AngularJS will throw an error underneath the hood if the bound value isn't a number. If you still need a work around, you can always modify the formatters and parsers of the binding—jsfiddle.net/1cxbnhv0 Commented Aug 2, 2018 at 3:07
  • You are right. I was hoping to see something out of the box to handle this case. I can always work around or have my own implementation Commented Aug 3, 2018 at 4:19

1 Answer 1

2

The ng-model directive is unable to clear the content of an <input type="number"> element when that content parses to NaN (not a number). This can happen when a user pastes invalid content or simply types "eee".

One fix is to add a custom directive:

app.directive('clearNan', function() {
  return {
    require: 'ngModel',
    link: function(scope, elem, attrs, ngModel) {
      ngModel.$formatters.push(function(value) {
        if (!value) elem.val(null);
        return value;
      });
    }
  };
})

Usage:

<input type="number" clear-nan ng-model="x" />

The DEMO

angular.module('numfmt-error-module', [])
.directive('clearNan', function() {
  return {
    require: 'ngModel',
    link: function(scope, elem, attrs, ngModel) {
      ngModel.$formatters.push(function(value) {
        if (!value) elem.val(null);
        return value;
      });
    }
  };
})
.run(function($rootScope) {
  $rootScope.typeOf = function(value) {
    return typeof value;
  };
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="numfmt-error-module">
  <input clear-nan type="number" ng-model="x" />
  <br>
  {{ x }} : {{ typeOf(x) }}
  <br>
  <button ng-click="x=''">Clear input</button>
</body>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.