角度过滤器返回一个对象。怎么避免呢?

时间:2016-11-24 06:00:18

标签: ng-repeat nested-loops

我有一个JSON文件,它的格式如下所示。有些值只是字符串,而其他值是具有键值对的对象。

[{ "question": "How many names do you have?", "answer": "1) Mark, 2) Ram, 3) Sam, 6) Paul, 7) Bob" }, { "question": "What are your habits?", "answer": [{ "id": 1, "value": "Coding" }, { "id": 2, "value": "Gaming" }, { "id": 3, "value": "Sleeping" }, { "id": 4, "value": "Enjoying good food" }] }, { "question": "What are you like?", "answer": "I'm a simple person who minds my own business." }, { "question": "What habit do you like most?", "answer": "I like coding the most." }]

我在html上的输出是as shown here (click to see image)这就是我想要的。我使用嵌套的ng-repeat来显示对象的正确值。
但是当我过滤这些结果时,显示的输出是一个json对象,而不是一个简单的列表,这是我不想要的。
我在过滤时在这里做的错误在哪里,我该如何避免呢?

请帮忙。 Full working code here

2 个答案:

答案 0 :(得分:0)

这是因为您过滤时问题的索引会发生变化。不使用counselingJson[$index].answer,而是使用qAndA.answer。工作人员:

https://plnkr.co/edit/cTCzUyS89b7KAh3RnAlM?p=preview

答案 1 :(得分:0)

我找到了代码的解决方案,请在json数组值后面加分号;

 {
        "question": "What habit do you like most?",
        "answer": "I like coding the most."
    }];

并且对于条件,您应该检查是否如下:

<div ng-if="isString(qAndA.answer)">
    {{qAndA.answer}}
</div>
<div ng-if="isArray(qAndA.answer)">
   <ul ng-repeat="a in counselingJson[$index].answer">
      <li><strong>{{a.id}})</strong> {{a.value}}</li>
   </ul>
</div>