Angular 식에서 문자열에서 Int로 해석하려면 어떻게 해야 합니까?
숫자 문자열 '5'
var num_str = '5';
해석 방법입력과 아래 답변을 동시에 맞히시겠습니까?
{{num_str + 1}} // 6
{{num_str - 1}} // 4
parseInt는 Angular 식에 사용할 수 없습니다.
{{parseInt(num_str) - 1}}
숫자 필터는 덧셈과 빼기를 할 수 없습니다.
{{num_str - 1 | number}}
도움이 될 만한 제안이 있으면 고맙게 생각하겠습니다.
컨트롤러 내:
$scope.num_str = parseInt(num_str, 10); // parseInt with radix
저는 앵귤러 필터를 사용하는 것을 선호합니다.
app.filter('num', function() {
return function(input) {
return parseInt(input, 10);
};
});
돔에서 사용할 수 있습니다.
{{'10'|num}}
여기 바이올린이 있습니다.
도움이 됐으면 좋겠네요!
다음 작업을 수행할 수 있습니다.
{{ 1 * num_str + 1 }}
또 다른 옵션은 다음과 같습니다.
$scope.parseInt = parseInt;
그러면 원하는 대로 할 수 있습니다.
{{parseInt(num_str)-1}}
이는 각진 표현은 다음 각도에 접근할 수 없기 때문입니다.window
~에게만scope
.
또한 숫자 필터에서는 식을 괄호로 감싸면 다음과 같이 동작합니다.
{{(num_str-1) | number}}
{{ num_str - 0 }}
...나한텐
위 중 어느 것도 나에게 통하지 않았다.
하지만 이것은 다음과 같습니다.
{{ (num1_str * 1) + (num2_str * 1) }}
javascript Number 메서드를 사용하여 번호로 해석할 수 있습니다.
var num=Number (num_str);
{{ 1 * num _ str + 1 } ( this this this like like like like like like (처음부터 제외) :
{{ num_str - 0 + 1}}
그러나 매우 취약하기 때문에 num_str에 문자가 포함되어 있으면 실패합니다.따라서 @hasassin의 말대로 필터를 쓰거나 데이터를 시작한 직후에 데이터를 전처리하는 것이 좋습니다.
파이프를 작성하여 시스템에서 원하는 위치에서 사용할 수 있습니다.
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);
} }
HTML에서
{{ attr.text | toNumber }}
모듈 파일에 이 파이프가 accessfull임을 선언하는 것을 잊지 마십시오.
component.ts 파일에서 사용
convertStringToInt(str){
var Num = parseInt(str);
return Num;
}
component.html에서 사용
convertStringToInt("2.4")
위에서 설명한 솔루션을 사용해 봤지만, 어느 솔루션도 효과가 없었습니다.JSON.parse를 사용했는데 작동했습니다.
$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 -- 1 }}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app>
{{'1'--1}}
</div>
언급URL : https://stackoverflow.com/questions/21398319/how-can-i-parse-string-to-int-in-an-angular-expression
'programing' 카테고리의 다른 글
Google Analytics - 리디렉션에 의한 아웃바운드 링크 추적 (0) | 2023.03.05 |
---|---|
호출 후 angularjs에서 $watch 바인딩 해제 (0) | 2023.03.05 |
각진 서비스에서는 어떻게 $on을 사용할 수 있습니까? (0) | 2023.03.05 |
SQLPLUS를 사용하여 CSV 형식의 파일로 스풀하려면 어떻게 해야 합니까? (0) | 2023.02.28 |
Angular를 사용하는 로그인 화면이 있는SPA의 예JS 및 ASP에 접속합니다.NET Web API 2? (0) | 2023.02.28 |