[javascript] How can I parse String to Int in an Angular expression?

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

This question is related to javascript angularjs

The answer is


You can create a Pipe and use it wherever you want in your system.

import { Pipe, PipeTransform } from '@angular/core';
 @Pipe({
     // tslint:disable-next-line:pipe-naming
     name: 'toNumber',
     pure: false }) export class ToNumberPipe implements PipeTransform { 
     public transform(items: any): any {
         if (!items) {
             return 0;
         }
         return parseInt(items, 10);
     } }

In the HTML

{{ attr.text | toNumber }}

Remember to declare this Pipe to be accessfull in your modules file.


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

var num=Number (num_str);

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

{{num_str -- 1 }}

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


{{ num_str - 0 }}

...works for me.


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);
});

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


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!


None of the above worked for me.

But this did:

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

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.