0

I am writing an app using Angular 1.3. I want to search through a table by any word/field; one search box for everything.

Currently I am able to get my search box to search through a specific field fine by doing:

<label>Search: <input ng-model="searchKeyword.title"></label>

or

<label>Search: <input ng-model="searchKeyword.author"></label>

Those work fine. However, when I try to search all the fields at the same time by doing:

<label>Search: <input type = "text" ng-model="searchKeyword"></label>

It doesn't work at all.

This is my code on the table:

  <label>Search: <input ng-model="searchKeyword"></label>

  <table ng-repeat="post in posts | orderBy: sort | filter: searchKeyword">
    <tr>
       <td> {{post.title}} </td>

       <td> {{post.author}} </td>

       <td> {{post.content}} </td>

       <td> {{post.date | date: "d/M/yyyy"}} </td>
    </tr>
  </table>

And this is inside my main controller:

 $scope.posts = posts.posts;
 $scope.searchKeyword = "";

Please tell me what exactly is causing this weird bug. Thank you.

OneMoreQuestion
  • 1,693
  • 3
  • 25
  • 51

2 Answers2

0

Its because ng-repeat create a new scope and cannot write in to a primitive property of its parent scope.but can write in to an object of its parent scope.

A scope (prototypically) inherits properties from its parent scope.

this post explains it well.What you want here is a custom filter check the ng-modal against each property in your object.

. filter('customFilter', function() {
return function(product,query) {
  var out = [];


    angular.forEach(product,function(value,key){

    if(value['author'].indexOf(query)>-1 || value['title'].indexOf(query)>-1)
    {
                out.push(value)
    }
    })
  return out;
}
})

Here is a working example

Community
  • 1
  • 1
Divya MV
  • 2,021
  • 3
  • 31
  • 55
  • Thank you. That is a really good read. So what can I do to solve this? I tried to do ng-model="$parent.searchKeyword" and ng-model="posts.searchKeyword", neither work! @Divya MV – OneMoreQuestion Jul 15 '15 at 06:49
  • Thanks for the example. I understand the logic behind this. However, when I do exactly this, I get the TypeError: Cannot read property 'indexOf' of undefined. and non of my posts load at all. Why might this be happening? @Divya MV – OneMoreQuestion Jul 15 '15 at 22:27
0

i found this post very late. Anyway my suggestion may helpful to other viewer. There is a solution for weird bug in weird way.

I found this post is very useful for use of multiple filters in controller with example of big data table search.

(after reading the above linked post) But you dont need to include multiple watcher and multiple input fields in every column of table, for your scenario you will just need the below code change after static json declaration.

$scope.$watch('searchKeyword', function(val) { $scope.items = $filter('filter')($scope.items2, val); });

considering searchKeyword is the ng-model of input field to search.

Manik
  • 1