Angularjs:在三元运算符中使用html元素

时间:2017-09-13 09:46:30

标签: javascript angularjs

我对Angular 1完全不熟悉,我想创建一个表,我从API中获取数据并将其显示在行中。我不想显示具有相同resourceId的多行,而是考虑创建一个下拉列表,我将点击该列表,并显示具有类似resourceId的所有行。

我已编写此代码以隐藏具有相同resourceId的行,但这不起作用,因为Angular似乎没有 支持在三元运算符中嵌入html元素。我怎样才能实现它?

<tr ng-repeat="report in data">
 {{report.resourceId === data[$index-1].resourceId ? 
 //Empty row
 :
 <td>{{report.reportId}}</td>
 <td>{{report.resourceId}}</td>
 <td>{{report.reason}}</td>
 }}
</tr>

数据数组如下:

data: [
  {
   reportId: "12",
   resourceId: "16241",
   reason: null
  },
  {
   reportId: "18",
   resourceId: "26387",
   reason: "It is biased or written by someone in the company"
  },
  {
   reportId: "19",
   resourceId: "26387",
   reason: "It is irrelevant"
  }
]

1 个答案:

答案 0 :(得分:2)

我认为您可以使用ng-if

而不是使用三元操作
<tbody ng-repeat="report in data">
<tr ng-if="report.resourceId !== data[$index-1].resourceId">

 <td>{{report.reportId}}</td>
 <td>{{report.resourceId}}</td>
 <td>{{report.reason}}</td> 
</tr>
<tr ng-if="report.resourceId === data[$index-1].resourceId">
   <td></td>
<tr>
</tbody>

演示

angular.module("app",[])
.controller("ctrl",function($scope){

$scope.arr = {data: [
  {
   reportId: "12",
   resourceId: "16241",
   reason: null
  },
  {
   reportId: "18",
   resourceId: "26387",
   reason: "It is biased or written by someone in the company"
  },
  {
   reportId: "19",
   resourceId: "26387",
   reason: "It is irrelevant"
  }
]}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<table>
 <tbody ng-repeat="report in arr.data">
<tr ng-if="report.resourceId !== arr.data[$index-1].resourceId">

 
 <td>{{report.reportId}}</td>
 <td>{{report.resourceId}}</td>
 <td>{{report.reason}}</td> 
</tr>
<tr ng-if="report.resourceId === arr.data[$index-1].resourceId">
   <td></td>
<tr>
</tbody>
</table>
</div>