programing

식에서의 Angularjs if-then-else 구조

minimums 2023. 2. 22. 21:40
반응형

식에서의 Angularjs if-then-else 구조

예를 들어 bool 값을 반환해야 하는 함수 $scope.isExists(항목)를 가지고 있는 등 angularjs 식에서 if-then-else 구문(삼진 연산자)을 사용할 수 있습니까?난 이런 걸 원해

<div ng-repeater="item in items">
    <div>{{item.description}}</div>
    <div>{{isExists(item) ? 'available' : 'oh no, you don't have it'}}</div>
</div>

문자열을 반환하는 함수를 사용할 수 있다는 것을 알고 있기 때문에 if-then-else 구문을 식에 사용할 수 있다는 것이 흥미롭습니다.감사해요.

각도 표현은 1.1.5 이전의 3진 연산자를 지원하지 않지만 다음과 같이 에뮬레이트할 수 있습니다.

condition && (answer if true) || (answer if false)

예를 들어 다음과 같은 방법이 있습니다.

<div ng-repeater="item in items">
    <div>{{item.description}}</div>
    <div>{{isExists(item) && 'available' || 'oh no, you don't have it'}}</div>
</div>

업데이트: Angular 1.1.5에서 3진 연산자에 대한 지원이 추가되었습니다.

{{myVar === "two" ? "it's true" : "it's false"}}

작은 플런커(예: 1.1.5)에서 설명한 것처럼 버전 1.1.5 이후 3진 연산자를 사용할 수 있습니다.

이력상의 이유로(아마도 plnkr.co가 장래에 어떠한 이유로 다운될 가능성이 있습니다) 제 예제의 주요 코드는 다음과 같습니다.

{{true?true:false}}

다음과 같이 ng-show를 쉽게 사용할 수 있습니다.

    <div ng-repeater="item in items">
        <div>{{item.description}}</div>
        <div ng-show="isExists(item)">available</div>
        <div ng-show="!isExists(item)">oh no, you don't have it</div>
    </div>

보다 복잡한 테스트의 경우 ng-switch 문을 사용할 수 있습니다.

    <div ng-repeater="item in items">
        <div>{{item.description}}</div>
        <div ng-switch on="isExists(item)">
            <span ng-switch-when="true">Available</span>
            <span ng-switch-default>oh no, you don't have it</span>
        </div>
    </div>

이것은 한 줄로 할 수 있습니다.

{{corretor.isAdministrador && 'YES' || 'NÂO'}}

의 사용방법td태그:

<td class="text-center">{{corretor.isAdministrador && 'Sim' || 'Não'}}</td>

키가 배열에 비스듬히 존재하는지 확인하려고 하는데, 이 질문으로 넘어갔습니다.내 Angularjs 1.4 3진 연산자는 다음과 같이 작동합니다.

{{ CONDITION ? TRUE : FALSE }}

따라서 어레이 키가 존재하기 위해 간단한 JS 체크를 했다.

솔루션 1:{{ array['key'] !== undefined ? array['key'] : 'n/a' }}

솔루션 2:{{ "key" in array ? array['key'] : 'n/a' }}

언급URL : https://stackoverflow.com/questions/16584346/angularjs-if-then-else-construction-in-expression

반응형