AngularJS Tutorial - Custom filter to check if input is an integer








The following code shows how to do custom filter to check if input is an integer.

Example


<!doctype html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
<script type='text/javascript'>
angular.module('myApp', ['filters']);
angular.module('filters', []).
filter('textOrNumber', function ($filter) {
    return function (input, fractionSize) {
        if (isNaN(input)) {<!--from   w  w w  .  j a  v  a  2 s .com-->
            return input;
        } else {
            return $filter('number')(input, fractionSize);
        };
    };
});
</script>
</head>
<body>
  <div ng-app="myApp">
    <input type="text" 
           ng-model="myText" 
           placeholder="add your text here" />
    <p>{{myText|textOrNumber:4}}</p>
</div>

</body>
</html>

The code above is rendered as follows: