2016-07-06 38 views
1

我有以下輸入數據:Angular - 按單個ng模型過濾,但在多個屬性上?

$scope.postList = [{ 
    name: "Hello World #1", 
    is_published: false, 
    targeting: false 
    }, { 
    name: "Hello World #2", 
    is_published: true, 
    targeting: true 
    }, { 
    name: "Hello World #3", 
    is_published: true, 
    targeting: true 
    }, { 
    name: "Hello World #4", 
    is_published: false, 
    targeting: true 
    }]; 

而現在,我應該能夠過濾結果從下面的選擇(使用ng-repeat顯示)。

<select ng-model="filterByCriteria"> 
    <option ng-value="published">Published</option> 
    <option ng-value="published">Unpublished</option> 
    <option ng-value="targeting">Custom Targeting</option> 
    <option ng-value="public">Public</option> 
</select> 

正如你可以看到,「發佈/ Unliblished」是關係到is_published財產,而「自定義定位/公共」是與targeting財產。

Plnkrhttp://plnkr.co/edit/Ej8qSGCUbts0RVVJspM1?p=preview

回答

3

你可以做這樣的事情: 添加這個新對象

$scope.filterByCriteria = [{ 
    is_published: true 
}, { 
    is_published: false 
}, { 
    targeting: true 
}, { 
    targeting: false 
}]; 

而在HTML

<body ng-app="myApp"> 
<div ng-controller="myController"> 
    <div> 
    Filter by: 
    <select ng-model="selectedCriteria"> 
     <option value="0">Published</option> 
     <option value="1">Unpublished</option> 
     <option value="2">Custom Targeting</option> 
     <option value="3">Public</option> 
    </select> 
    </div> 
    <ul> 
    <li ng-repeat="post in postList | filter: filterByCriteria[selectedCriteria]"> 
     {{post.name}} 
    </li> 
    </ul> 
</div> 

Here is an example

+0

你測試過了嗎? – developer033

+1

@ developer033是的,它的工作原理。 – Titus

+0

真的,很好的解決方案。如果他不能創建這個對象(在他不知道對象數組包含什麼屬性的情況下),這只是一個問題,當然,這只是一個例子。 – developer033