Angular interating 2种不同类型的数组 - 单个ng-repeat

时间:2016-12-02 11:01:16

标签: javascript html angularjs arrays json

我有一个json,它包含字符串数组和json对象数组,如代码所示。必须使用ng-repeat迭代它并且需要显示字符串值,如果数组是字符串,并且如果数组是json对象则需要显示特定键的值。请帮助!

<html ng-app>
    <head>
    <script src="https://code.angularjs.org/1.4.9/angular.js">
      </script>
    </head>
    <body>
<div ng-init="data=[
              {'name':'Name1','filterValues':['eq1','eq2','eq3','eq4','eq5','eq6']},
              {'name':'Name2','filterValues':[{'id':'eid1','description':'Description 1'},{'id':'eid2','description':'Description 2'},{'id':'eid3','description':'Description 3'},{'id':'eid4','description':'Description 4'},{'id':'eid5','description':'Description 5'}]}
              ]">
       <div data-ng-repeat="d1 in data" >{{d1.name}}
          <div data-ng-repeat="d2 in d1.filterValues"> {{d2}}</div>
        </div>

<span style="color:tomato">"Here, under Name2, I need only the Description Values" </span>
  </div>
  </body>
</html>

1 个答案:

答案 0 :(得分:2)

您需要检查迭代元素是否具有id属性。基于该显示d2.descriptiond2。可以使用?条件运算符完成,如下所示。

{{d2.id?d2.description:d2}}

<html ng-app>
    <head>
    <script src="https://code.angularjs.org/1.4.9/angular.js">
      </script>
    </head>
    <body>
<div ng-init="data=[
              {'name':'Name1','filterValues':['eq1','eq2','eq3','eq4','eq5','eq6']},
              {'name':'Name2','filterValues':[{'id':'eid1','description':'Description 1'},{'id':'eid2','description':'Description 2'},{'id':'eid3','description':'Description 3'},{'id':'eid4','description':'Description 4'},{'id':'eid5','description':'Description 5'}]}
              ]">
       <div data-ng-repeat="d1 in data" >{{d1.name}}
          <div data-ng-repeat="d2 in d1.filterValues"> {{d2.id?d2.description:d2}}</div>
        </div>

<span style="color:tomato">"Here, under Name2, I need only the Description Values" </span>
  </div>
  </body>
</html>