javascript – How can I parse String to Int in an Angular expression?-ThrowExceptions

Exception or error:

A number string ‘5’

var num_str = '5';

How can I parseInt and let below answers correct at the same time?

{{num_str + 1}}  // 6
{{num_str - 1}}  // 4

parseInt can’t be used in an Angular expression,

{{parseInt(num_str) - 1}}    

number filter can’t do add and minus,

{{num_str - 1 | number}}

If anyone have useful suggestion, I will very appreciate of you

How to solve:

In your controller:

$scope.num_str = parseInt(num_str, 10);  // parseInt with radix

###

I prefer to use an angular filter.

app.filter('num', function() {
    return function(input) {
      return parseInt(input, 10);
    };
});

then you can use this in the dom:

{{'10'|num}}

Here is a fiddle.

Hope this helped!

###

You can try:

{{ 1 * num_str + 1 }}

http://jsfiddle.net/Z32fP/

###

Another option would be:

$scope.parseInt = parseInt;

Then you could do this like you wanted:

{{parseInt(num_str)-1}}

This is because angular expressions don’t have access to the window, only to scope.

Also, with the number filter, wrapping your expression in parentheses works:

{{(num_str-1) | number}}

DEMO

###

{{ num_str - 0 }}

…works for me.

###

None of the above worked for me.

But this did:

{{ (num1_str * 1) + (num2_str * 1) }}

###

You can use javascript Number method to parse it to an number,

var num=Number (num_str);

###

Besides {{ 1 * num_str + 1}}
You can also try like this(minus first):

{{ num_str - 0 + 1}}

But the it’s very fragile, if num_str contains letters, then it will fail. So better should try writing a filter as @hassassin said, or preprocess the data right after initiating it.

###

I tried the solutions mentioned above and none of them worked for me. I used JSON.parse and it worked:

$http.get('/api/getAdPolling')
  .success(function (data) {
    console.log('success: ' + data.length);

    if (JSON.stringify(data) != "not found") {
        $scope.adPoll = JSON.parse(data);
    }
})
  .error(function (data) {
    console.log('Error: ' + data);
});

###

Not really great but a funny hack:
You can — instead of +

{{num_str -- 1 }}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app>
  {{'1'--1}}
</div>

Leave a Reply

Your email address will not be published. Required fields are marked *