Search code examples
angularjsangular-filters

How to filter on multiple fields in AngularJS using $filter('filter')


I am creating a site with a search using the query filter in AngularJS. I have found many tutorials on how to implement this search in one field, but none that explain how to search across multiple fields. But not working

i want to search using multiple fields with OR logic. If i give name in search box will filter by post_name, if i give category in search box will filter by post_category like this.

home.html

<form ng-submit="submitForm()">
                    <div class="form-group">
                        <input class="form-control" type="text" placeholder="Search" name="searchtxt" ng-model="searchtxt">
                    </div>    
                    <div class="btn-block text-right">
                      <button type="submit" class="btn btn-primary">Submit</button>
                    </div>
                </form>

search.html

<div class="col-md-4 col-sm-6 col-xs-12" ng-repeat="blog in blogposts">
    <article class="blogPost">
        <a href="#/{{blog['post_title']}}"><img src="{{blog['post_image']}}"/></a>
         <div class="inner-content">
                                <h3 class="entry-header">
                                    <div class="post-date">
                                        <span class="post-month">{{blog['post_date'] | dateToISO | date:"MMM"}}</span>
                                        <span class="post-day">{{blog['post_date'] | dateToISO | date:"d"}}</span>
                                    </div>
                                    <a href="#/{{blog['post_title']}}">{{blog['post_title']}}</a>
                                </h3>
                                <div class="body-post">{{blog['post_content'] | limitTo:150}}...</div>        
                                <h5>
                                    <span class="pull-left">
                                            <i class="fa fa-clock-o"> {{blog['post_date'] | dateToISO | date:"d MMM y, h:mm:ss a"}}</i> 
                                            <i class="fa fa-tag cattag"> {{blog['category_name']}}</i>
                                    </span>
                                </h5>
                            </div>
    </article>

data.json

[
   {
    "post_id":1,
    "post_title": "Blog Post One",
    "post_content":  "Lorem ipsum dolor sit amet",
"post_category" : "business",
    "post_author": "Nick Moreton",
    "post_image":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS0_AIUUg4B7vVSj1E-A0SA_yrsxmvKLQZKgIKu1dOJ3MAXb4J8",
    "post_date":"2015-12-27 02:23:20"
    },
   {
    "post_id":2,
    "post_title": "Blog Post Two",
    "post_content":  "Lorem ipsum dolor sit amet",
"post_category" : "business",
    "post_author": "Nick Moreton",
    "post_image":"http://i.imgur.com/ZqFeKWv.jpg",
    "post_date":"2015-08-17 02:23:20"
     },
   ]

app.js

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

   app.config([ '$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {   
    $routeProvider      
    .when('/',{
            templateUrl : 'home.html',
            controller: 'HomeController'
    })
    .when('/search',{
            templateUrl : 'search.html',
            controller: 'SearchController'
    })
    .otherwise({
        redirectTo : '/'
    });
    } 
   ]);

  app.filter('dateToISO', function() {
    return function(input) {
    input = new Date(input).toISOString();
    return input;
   };
  });

   app.controller('HomeController', function($scope,$http,$location,$rootScope) {

      $scope.submitForm = function(){
        $rootScope.blogSearch = $scope.searchtxt;
        console.log($scope.blogSearch);
        $location.path('/search');
      };

    });

    app.controller('SearchController', 
      function($scope,$http,$location,$rootScope,$filter) {
       $http({
            method:'GET', 
            url:'data.json'
        })
        .success(function(response){
                $scope.blogposts = $filter('filter')(response, {post_title:$rootScope.blogSearch},{post_content:$rootScope.blogSearch},{post_category:$rootScope.blogSearch});

            console.log($scope.blogposts);  
        })
     });

Solution

  • Edit:

    Some thing is wrong with the filter. Please try this below code.

    //  $scope.blogposts = $filter('filter')(response, { 'post_title': $rootScope.blogSearch }, { 'post_content': $rootScope.blogSearch }, { 'post_category': $rootScope.blogSearch });
                    $scope.blogposts = [];
                    for (var i = 0; i < response.length; i++)
                    {
                        if(response[i].post_title == $rootScope.blogSearch || response[i].post_content == $rootScope.blogSearch ||response[i].post_category == $rootScope.blogSearch)
                        {
                            $scope.blogposts.push(response[i]);
                        }
                    }
                    console.log($scope.blogposts);