Search code examples
javascriptangularjsangular-filters

Filter array by clicking on categories list


Looking to have a long array of products with a selction of categories at the top. When clicked they will show only within that category.

Can anyone help with tweaking this code based on a simple example to filter by clicking buttons.

So when fruit button is clicked only Fruit products displayed, when Nuts button, only nuts..

        <html ng-app="app">
            <body ng-controller="main">
            <div>Fruit / Nut</div><br>
                <a ng-click="filters.category = ''">clear filter</a>
            <div ng-repeat="link in links | filter:filters">

                    <strong>{{link.name}}</strong>
                    <a ng-click="filters.category = link.category">{{link.category}}</a>
                </div>
            </body>
        </html>

        var app = angular.module('app', []);

        app.controller('main', function($scope) {
            $scope.filters = { };

            $scope.links = [
                {name: 'Apple', category: 'Fruit'},
                {name: 'Pear', category: 'Fruit'},
                {name: 'Almond', category: 'Nut'},
                {name: 'Mango', category: 'Fruit'},
                {name: 'Cashew', category: 'Nut'}
            ];
        });

http://jsfiddle.net/oxbzuz4v/


Solution

  • Will it be something like this?

    <html ng-app="app">
    <body ng-controller="main">
    <div>
    <button ng-click="filters.category ='Fruit'">Fruit</button>
    <button ng-click="filters.category ='Nut'">Nut</button>
    <button ng-click="filters.category =''">Clear filter</button>
    </div><br>
       <div ng-repeat="link in links | filter:filters">
            <strong>{{link.name}}</strong>
        </div>
    </body>
    

    The rest stays the same... Demo