2016-07-27 42 views
2

我想要做的是創建一個可以基於嵌套在JSON對象數組中的類別進行過濾的概述。Angular JS過濾基於類別數組的概述

我想創建的概況看起來像這樣的項目的JSON:

{ 
    id: 1, 
    title: "title", 
    content: "content", 
    categories: [{ 
     title: "cat1", 
     descripton: "desc" 
    }, 
    { 
     title: "cat2", 
     descripton: "desc" 
    }] 
}, 
{ 
    id: 2, 
    title: "title", 
    content: "content", 
    categories: [{ 
     title: "cat3", 
     descripton: "desc" 
    }, 
    { 
     title: "cat4", 
     descripton: "desc" 
    }] 
} 

的HTML看起來是這樣的:

<select ng-model="catselect"> 
    <option>cat1</option> 
    <option>cat2</option> 
    <option>cat3</option> 
    <option>cat4</option> 
</select> 
<ul> 
    <li ng-repeat="item in array | filter: {ARRAY OF CATEGORIES: catselect}"> 

    </li> 
</ul> 

目前我不知道如何讓這個工作。 (我認爲)最明顯的解決方案應該有點像filter: {categories.title: catselect},但顯然不是。據我所知在Stackoverflow上沒有其他問題可以解決這個問題。我很感興趣,看看有沒有人可以幫助我。

回答

0

你能試試看看它是否有效嗎?我沒有實際測試過它。

filter: { categories: { title: catselect } } 
+0

感謝您的煩惱!這個解決方案的解決方案雖然不工作,但:( –

+0

嘗試我的答案的變體像:filter:{categories:{title:catselect}}或其他人,這實際上爲我工作時,我有我的對象內的對象,沒有嘗試與數組裏面的對象.. –

+0

這實際上起作用!:)你能編輯你的答案,所以我可以接受它嗎? –

0

一個自定義過濾器將工作

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

 
    $scope.array = [{ 
 
     id: 1, 
 
     title: "title", 
 
     content: "content", 
 
     categories: [{ 
 
     title: "cat1", 
 
     descripton: "desc" 
 
     }, { 
 
     title: "cat2", 
 
     descripton: "desc" 
 
     }] 
 
    }, { 
 
     id: 2, 
 
     title: "title2", 
 
     content: "content", 
 
     categories: [{ 
 
     title: "cat3", 
 
     descripton: "desc" 
 
     }, { 
 
     title: "cat4", 
 
     descripton: "desc" 
 
     }] 
 
    }] 
 
    }) 
 
    .filter("filterByCat", function() { 
 
    return function(input, catselect) { 
 
     if (catselect != undefined) { 
 
     var f = [] 
 
     angular.forEach(input, function(el) { 
 
      if ((el.categories.filter(function(cat) { 
 
      return cat.title == catselect 
 
      })).length > 0) f.push(el); 
 
     }) 
 
     return f; 
 
     } else { 
 
     return input; 
 
     } 
 
    } 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="app" ng-controller="test"> 
 
    <select ng-model="catselect"> 
 
    <option>cat1</option> 
 
    <option>cat2</option> 
 
    <option>cat3</option> 
 
    <option>cat4</option> 
 
    </select> 
 
    <ul> 
 
    <li ng-repeat="item in array | filterByCat:catselect">{{item.title}}</li> 
 
    </ul> 
 
</div>