AngularJS Search Filter performed 2 Ways

Demonstration of AngularJS filtering on a list of products by free-form entry or by a user selected button based on product categories.

by Michael Conroy

HTML

<div ng-controller="myCtrl">
    Free Form Search: <input type="text" ng-model="search" placeholder="Search" />
    <div>
        Filter By Category: 
        <button ng-repeat="cat in categories" ng-click="$parent.category=cat">{{cat}}</button>
       
    </div>
    <table cellpadding="5" cellspacing="0" border="1">
        <tr>
            <th>Product</th>
            <th>Category</th>
        </tr>
        <tr ng-repeat="product in products | filter:search | filter:category | orderBy:'name'">
            <td>{{product.name}}</td>
            <td>{{product.category}}</td>
        </tr>
    </table>
</div>

CSS

table tr:nth-child(even) {
    background-color: #eeeeee;
}

JavaScript

angular.element(document).ready(function(){

    angular.module('myApp',[])
        .controller('myCtrl', ['$scope','store',function ($scope,store) {
            $scope.search = '';
            $scope.products = [];
            $scope.categories = [];
            $scope.category = '';
            
            $scope.categories = store.getCategories();
            $scope.products = store.getProducts();     
            
        }])
        // fake service, substitute with your server call ($http)
        .factory('store',function(){
            var categories = ['Fruit','Vegetables','Dairy'];
            var products = [
                {name: 'Apples',category: 'Fruit'},
                {name: 'Pears',category: 'Fruit'},
                {name: 'Grapes',category: 'Fruit'},
                {name: 'Potato',category: 'Vegetables'},
                {name: 'Green Beans',category: 'Vegetables'},
                {name: 'Broccoli',category: 'Vegetables'},
                {name: 'Milk',category: 'Dairy'},
                {name: 'Yogurt',category: 'Dairy'},
                {name: 'Cheese',category: 'Dairy'},
            ];
            return {
                getCategories : function(){
                    return categories;
                },
                getProducts : function(){
                    return products;
                }
            };
        });
    
    angular.bootstrap(document,['myApp']);
});