I am using AngularFire for taking inputs and saving them to my Firebase database. Currently, I have an input for entering the price of a service, like so (I am using an input type of "text" instead of "number", since I don't want it to cause problems in older browsers):
<p><input type="text" placeholder="Enter your monthly price here" ng-model="priceMonthly" required/></p>
However, when I write this to my Firebase upon form submission (using the update function), it writes the value $scope.priceMonthly
as a string instead of an integer. What's the best way to write this value as an integer instead of a string?
What about type="number"
, like:
<input type="number" ng-model="myText" name="inputName">
Since you want to make to user write numbers only. The $scope.myText
should be the number in this case.
as a side note:
to be sure that you sent integer, print the value on the screen like:
<pre>myText as number: {{priceMonthly|json}}</pre>
if the value is wrapped with quotes - its a string, none - number.
Just convert it to integer:
var priceMonthly = parseInt($scope.priceMonthly, 10);
For any input type other than "number" (text, range, etc), you could add a $parser to your input, which will cast it's value for you:
angular.module('exampleApp', [])
.controller('ExampleCtrl', function ($scope) {
$scope.filter = {
number: 10
};
})
.directive('castToInteger', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$parsers.unshift(function(value) {
return parseInt(value, 10);
});
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="exampleApp">
<div ng-controller="ExampleCtrl">
<input type="range" min="1" max="100" ng-model="filter.number" cast-to-integer="true" />
<p>{{filter | json}}</p>
</div>
</div>
Another answer on the topic: https://stackoverflow.com/a/16187142/818862
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With