1

I have a form with several inputs. It works fine but the problem comes when I fill the input with the number 0. Other numbers are good. 1 is interpreted "1" etc.

Only problem is 0. I would like to force value to string even if it's 0.

 <input type="text" ng-model="project.cible" required />

Result :

 { 
   cible: 0
 }

Instead :

 { 
   cible: "0"
 }
3
  • 1
    Check this plunkr not able to reproduce what you are saying Commented May 13, 2014 at 17:00
  • I don't understand why it works for you. I have the same code. My result sends : 0 instead "0" Commented May 14, 2014 at 12:40
  • what do you mean exactly when you say result sent? Can you give more details/ try to replicate the same in a fiddle. Commented May 14, 2014 at 12:43

2 Answers 2

0

By default, all values from an input tag are strings. This is true for every browser. If you want to convert the value to an int, use parseInt(value). If you want to convert the value to a float, use parseFloat(value). Before you do either of those, you should check to be sure it is a number. Your other option is to change the type of the input to number.

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

Comments

0

I think it's best to keep your model values as numbers instead of strings if it makes sense from a data modelling perspective. That way you can do sums, comparisons etc more easily even in places were you don't have enough control to write javascript conversion code, like an expression:

<div ng-show="project.cible + project.someOtherNum > 0">I'm visible</div>

This can be done by changing the input type to type="number". Angular has a special directive for this case which (among other things) adds a parser/formatter in the associated ngModelController:

ctrl.$parsers.push(function(value) {
    var empty = ctrl.$isEmpty(value);
    if (empty || NUMBER_REGEXP.test(value)) {
        ctrl.$setValidity('number', true);
        return value === '' ? null : (empty ? value : parseFloat(value));
    } else {
        ctrl.$setValidity('number', false);
        return undefined;
    }
});

ctrl.$formatters.push(function(value) {
    return ctrl.$isEmpty(value) ? '' : '' + value;
});

Valid input is converted to float prior to updating the model property, and model properties are converted to strings prior to updating the DOM element.

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.