title: Input element that allowes only number with decimals, with AngularJS
body: <p>I'm trying to create an input element that:</p>
  
  <ul>
  <li>Holds a number (string or actual number doesn't matter).</li>
  <li>You shall not be able to enter anything else but numbers and a dot(.).</li>
  <li>You are allowed to enter two decimals.</li>
  <li><p>If no decimals are entered, two decimals (i.e. .00) shall be added to the number when leaving the input element (on-blur).</p></li>
  <li><p>I'm working with AngularJS (1.2) and watch $valid and $invalid on the containing form.</p></li>
  <li><p>The input is valid when the value is a number with two decimals and the value is larger than 0.</p></li>
  </ul>
  
  <p>I have tried to use:</p>
  
  <pre><code>&lt;input ng-model="price" type="number" ng-blur="addDecimals()"/&gt;
  
  $scope.addDecimals = function(){
    $scope.price = $scope.price.toFixed(2);
  }
  </code></pre>
  
  <p>But then I can't add zeroes as decimals (.00). As toFixed() returns a string, the value is not allowed in the input and it becomes empty.</p>
  
  <p>I have also tried to use </p>
  
  <pre><code>&lt;input type="text" ng-model="price" ng-blur="addDecimals()" ng-change="changed()" /&gt; 
  
  $scope.changed = function(){
      // removes all charachters but numbers and one dot (.);
      // examples: 
      //  if value is '1a.t9' it will be changed to '1.9'
      //  if value is 'qwe' it will be changed to ''
      //  if value is 4 it will not be changed.
      $scope.price = removeAllCharsButNumbersAndDot($scope.price);
  }
  
  $scope.addDecimals = function(){
     if(parseFloat($scope.price) &gt; 0) 
       $scope.price = $scope.price.toFixed(2);
     else
       $scope.price = "";
  }
  </code></pre>
  
  <p>With this solution [form].$valid will be set to true if the value '0' is entered. [form].$valid will be set to false only when the user leaves the input element (on-blur) which is kind of ugly.</p>
  
  <p>I have tried to use ng-pattern="/^\s*(?=.<em>[1-9])\d</em>(?:.\d{1,2})?\s*$/", but then ng-change will not fire.</p>