如何在AngularJS中的数据绑定中设置条件?

如何在AngularJS中的数据绑定中设置条件?,angularjs,Angularjs,我想做以下工作: <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

我想做以下工作:

<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>

{{row.id}}
{{if(row.testTypeId==1){test.tests.dataMap[row.examId].name;}}
{{if(row.testTypeId==2){test.topic.topicNameMap[row.topicId]}}

然而,这给了我一个关于{{}的{内部的错误。有没有其他方法可以让它工作呢?

三元运算符当然可以工作


您可以使用ng show执行以下操作:

<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>

{{row.id}}
{{test.exams.dataMap[row.examId].name}
{{test.topics.topicNameMap[row.topicId]}

@jack.the.ripper是正确的。将逻辑移到$scope中的函数,然后调用该函数

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

{{ name(row) }}

为什么它需要在数据绑定本身中?您不能只使用
ng if
指令吗

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

我建议将逻辑保留在控制器中,避免复杂的表达式我确实尝试过使用函数,但后来我发现行未定义存在一些问题。除非将行传递到函数中,否则行未定义。请参见下面我的答案,我就是这样做的。确实如此,但您肯定不想过度使用它们。Otherwise你开始把你的代码放到模板中。
===
==
更受欢迎。我正在做一个确切的例子,但你比我更成功了。这是一个更好的方法。它是用声明式编程的常规方法来做的。
<div ng-if="row.testTypeId == 1">stuff</div>
<div ng-if="row.testTypeId == 2">otherstuff</div>