user1464139
user1464139

Reputation:

How can I put a condition inside a data binding in AngularJS?

I would like to do the following:

<div>
    <div ng-repeat="row in test.active">
        <div>{{ row.id }}</div>
        <div>
            {{ if (row.testTypeId == 1) { test.exams.dataMap[row.examId].name; } }}
            {{ if (row.testTypeId == 2) { test.topics.topicNameMap[row.topicId] } }}
        </div>
    </div>
</div>

However this is giving me an error with the { inside of the {{ }}. Is there another way I could make this work?

Upvotes: 2

Views: 12178

Answers (4)

callmehiphop
callmehiphop

Reputation: 646

Why does it need to be in the databinding itself? Couldn't you just use the ng-if directive?

<div ng-if="row.testTypeId == 1">stuff</div>
<div ng-if="row.testTypeId == 2">otherstuff</div>

Upvotes: 0

John Munsch
John Munsch

Reputation: 19528

@jack.the.ripper is correct. Move the logic to a function in the $scope and call that instead.

$scope.name = function (row) {
  if (row.testTypeId == 1) {
    return test.exams.dataMap[row.examId].name;
  } else {
    return '';
  }
}

In the HTML:

{{ name(row) }}

Upvotes: 7

dustyrockpyle
dustyrockpyle

Reputation: 3184

You can use ng-show to do this:

<div>
    <div ng-repeat="row in test.active">
        <div>{{ row.id }}</div>
        <div ng-show="row.testTypeId == 1">
            {{test.exams.dataMap[row.examId].name }}
        </div>
        <div ng-show="row.testTypeId == 2">
            {{ test.topics.topicNameMap[row.topicId] }}
        </div>
    </div>
</div>

Upvotes: 2

user2882597
user2882597

Reputation: 424

Ternary operators certainly work, plnkr.

{{ (row.testTypeId == 1) ? test.exams.dataMap[row.examId].name : '' }}
{{ (row.testTypeId == 2) ? test.topics.topicNameMap[row.topicId] : '' }}

Upvotes: 4

Related Questions