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

276441 次浏览

In your controller:

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

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

var num=Number (num_str);

You can try:

\{\{ 1 * num_str + 1 }}

http://jsfiddle.net/Z32fP/

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!

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.

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

None of the above worked for me.

But this did:

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

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);
});
\{\{ num_str - 0 }}

...works for me.

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>

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.

Use in component.ts file

convertStringToInt(str){
var Num = parseInt(str);
return Num;
}

Use in component.html

convertStringToInt("2.4")