6

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?

3 Answers 3

11

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

Sign up to request clarification or add additional context in comments.

2 Comments

Nice solution, but I am trying to do the same thing with an <option>'s value attribute from a <select> element instead of a plain old <input>. Any idea's for the select?
what if the input type is hidden?
1

Just convert it to integer:

var priceMonthly = parseInt($scope.priceMonthly, 10);

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.