cjs1976 cjs1976 - 4 months ago 55
AngularJS Question

ionic + variable with number produces always 'is not a valid number'

In my page I use variables from the controller of the page. For example:

<label class="item item-input item-stacked-label">
<span class="input-label">Projekt Id:</span>
<input type="number" placeholder="0" value="{{cpc.projektid}}" disabled>
</label>


The controller does some calculation over a factory, and get's also some data from an SQLite database. If I check the type of my variables in the controller or in the factory, i get for Example:

console.log(typeof cpcVm.projektid); => number
console.log(angular.isNumber(cpcVm.projektid)); 0> true


So for me, this means, that the value of the variable is a number!?

But I get always the warning:


The specified value "{{cpc.projektid}}" is not a valid number. The
value must match to the following regular expression:
-?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?"


For the
projektid
this is not a big issue, but I have more complicated calculations, and I need also set some filters, which work only if the number is a number. For example:

<input type="number" placeholder="0" value="{{cpc.luftmenge | number:2}}" disabled>


I tried already to give an additional
parseFloat()
in my controller and the factory, but there is no change. The controller and the factory say it's a number, but in the HTML it creates an error, and I can't use the filter.

Another strange thing: If I set the value of the variable in the factory or the controller manually (for example return 12;), then it works.

Any ideas?

Answer

Use ng-value="cpc.projektid" instead of value attribute.

Till the Angular is not loaded in the page, what browser will see in the value attribute is {{cpc.projektid}} and that is why it is complaining. ng-value make sure that value attribute is only get added after the expression compiles properly.

var app = angular.module("sa", []);

app.controller("FooController", function($scope) {

  $scope.projektid = "2"
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="sa" ng-controller="FooController">
  Projekt Id:
  <input type="number" placeholder="0" ng-value="projektid" disabled>
</div>

Comments