Kévin Duguay
Kévin Duguay

Reputation: 761

How to use condition in expression in AngularJS

I'm making a small page that show how the number filter work:

Number: <input type="text" ng-model="nomber"><br/>
fractionSize: <input type="text" ng-model="fractionSize"><br/>
gives: {{ nomber | number:fractionSize }}

If i write a number, it will work, but if I decide to had a nomber in fractionSize, but than remove it, it gives me NaN.

I would like to have a condition in

{{ nomber | number:fractionSize }}

that will tell my condition to not try to use fractionSize if the input is empty.

Upvotes: 0

Views: 680

Answers (2)

Moid
Moid

Reputation: 1447

Use type="number"instead of text.

<input type="number" min="0" ng-model="fractionSize">

I think that should solve your problem for NaN. And as you say that it works for number, it should solve your problem.

And if you want to add a condition instead then:

Number: <input type="number" ng-model="nomber"><br/>
fractionSize: <input type="number" min="0" required ng-model="fractionSize"><br/>
    gives: <span ng-if="typeOf nomber ==='number'">{{ nomber | number:fractionSize }}</span>

Here is the working fiddle.

Upvotes: 0

Stefano Saitta
Stefano Saitta

Reputation: 2014

You should redefine the filter you are using, cause by design angular would return NaN, as you can see here: Number filter should not format NaN to empty string

Here a custom filter that accomplish what are you looking for:

angular.module('plunker', [])
  .controller('MainCtrl', function($scope) {
    $scope.nomber = 0;
    $scope.fractionSize = 0;
  })
.filter('textOrNumber', function ($filter) {
    return function (input, fractionSize) {
        if (isNaN($filter('number')(input, fractionSize))) {
            return $filter('number')(input, 1);
        } else {
            return $filter('number')(input, fractionSize);
        };
    };
});
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script data-require="angular.js@1.*" data-semver="1.4.0" src="https://code.angularjs.org/1.4.0/angular.js"></script>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    Number: <input type="number" ng-model="nomber"><br/>
    fractionSize: <input type="number" ng-model="fractionSize"><br/>
    gives: {{ nomber | textOrNumber: fractionSize}}
  </body>

</html>

EDIT: An improvements can be, if we consider that and empty denominator in a fraction can be evaluated as 1, so you can edit your code returning $filter('number')(input, 1); when isNan() has evaluated true.

Here you can find a working plunkr.

Upvotes: 1

Related Questions