userMod2 userMod2 - 5 months ago 15
AngularJS Question

Angular - Check if value entered into a field is a number

In my Angular app I have a field that accepts either an email address or a phone number.

If a number is entered I want to show a particular span. However I can't seem to get this working.

So in my controller I have written:

$scope.isNumber = function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}


Then in my HTML I have:

<form name="registrationForm">

<div>
Email or Mobile
<span ng-show="isNumber(registrationForm.usernameReg)">Include the country code.</span>
</div>

<input name="usernameReg" ng-change="main.change()" type="text" ng-model="main.username">

</form>


Any ideas why this wouldn't work?

Thanks.

Answer

You need to be testing the value of the model.

try

ng-show="isNumber(main.username)"

registrationForm.usernameReg is an object that contains numerous properties used as part of validation.

To better see this add <pre>{{registrationForm |json}}</pre> in your view