Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Angular ng-model to integer when writing to Firebase

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?

like image 446
user2793297 Avatar asked Nov 10 '13 20:11

user2793297


3 Answers

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.

enter image description here

like image 81
Maxim Shoustin Avatar answered Nov 18 '22 16:11

Maxim Shoustin


Just convert it to integer:

var priceMonthly = parseInt($scope.priceMonthly, 10);
like image 1
tymeJV Avatar answered Nov 18 '22 17:11

tymeJV


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

like image 1
Jonas Masalskis Avatar answered Nov 18 '22 17:11

Jonas Masalskis