2014-12-30 81 views
0

返回对象的属性我有很多对象的JavaScript数组,像这样:聚合物获得通过过滤器

var myArray = [ 
    { 
     "id": 1, 
     "name": "Name 1", 
     "active": false 
    },{ 
     "id": 2, 
     "name": "Name 2", 
     "active": true 
    },{ 
     "id": 3, 
     "name": "Name 3", 
     "active": false 
    } 
] 

我使用这些对象的id参数对它们进行比较和存储的值。要获得属于该ID的对象,我写了一个过滤器:

getTest: function(id){ 
    var result = this.tests.filter(function(o){return o.id == id;}); 
    return result ? result[0] : null; 
} 

因此,我可以轻松地使用此过滤器内联。现在我想获得内联过滤结果的属性,例如:

<template if="{{ { id | getTest }.active"> 
    You are active! 
</template> 

但是,这样做会导致无效表达式。我已经通过docs多次阅读,但不太清楚这是否甚至可能。

我该怎么做?

回答

1

您可以使用ID参数制作自定义过滤器。该过滤器将采取该项目,验证它是否有良好的ID,并验证它是否有效。

我原来的例子就是在这样的Plunker http://plnkr.co/edit/FSwzndyjRxJIymehsZIg?p=preview

希望它能帮助!如果不是正是你想做的事,请你,我会尽力回答进一步:)

[编辑]

OK,阅读您的意见后,这个怎么样:

<template is="auto-binding"> 

    <h1>Hi !</h1> 
    <template repeat="{{item in myArray}}"> 
     <template if="{{ item.active }}"> 
     <p> 
     Item id:{{item.id}} is active! <br> 
     Amount of steps in this test: {{ item.steps }} <br> 
     Test description: {{ item.description }} 
     </p> 
     </template> 
    </template> 
    </template> 

    <script> 
    var template = document.querySelector('template[is="auto-binding"]'); 
    template.count=0; 
    template.myArray = [ 
     { 
     "id": 1, 
     "name": "Name 1", 
     "active": false, 
     "steps": 3, 
     "description": "Lorem" 
     },{ 
     "id": 2, 
     "name": "Name 2", 
     "active": true, 
     "steps": 4, 
     "description": "Ipsum" 
     },{ 
     "id": 3, 
     "name": "Name 3", 
     "active": true, 
     "steps": 5, 
     "description": "Lorem Ipsum" 
     } 
    ]; 
</script> 

那么你得到的输出你想要的:

Item id:2 is active! 
Amount of steps in this test: 4 
Test description: Ipsum 

Item id:3 is active! 
Amount of steps in this test: 5 
Test description: Lorem Ipsum 

的Plunker是http://plnkr.co/edit/nBYeeZ2Uw0EFihAhNYpl?p

+0

的问题是这需要我为每个属性编写一个过滤器?我的实际对象有超过10个属性,我都需要访问某处,例如显示价格,结果,步骤等......此外,我包含的过滤器确实有效,但我不知道是否可以访问该对象属性而无需制作额外的过滤器。 – jdepypere

+0

只有一个过滤器可以使用尽可能多的属性进行过滤。请给我描述一个你想要的例子,我会代码:) – LostInBrittany

+0

那么目前我有作为一个数组的索引,所以我可以做'模板if =“{{myArray [id] .active }}“>”轻松地在一行中检查对象的属性。或者我也可以很容易地显示其他数据:'此测试中的步骤数量:{{myArray [id] .steps}}','测试描述:{{myArray [id] .description}}'等等。 – jdepypere