1
votes

I have a table that displays user information. We have a search box at the top that allows user to enter text and select type to search from the dropdown.

<input type="text" ng-model=search>
<select ng-model=searchBy>
    <option value="$">All</option>
    <option value="Name">Name</option>
    <option value="DoB">Date of birth</option>
    <option value="Hobbies">Hobby</option>
</select>

<div ng-repeat="user in users | filter:searchFilter">
    <div>{{user.Name}}</div>
    <div>{{user.DoB | date: "MM/dd/yyyy"}}</div>
    <div ng-repeat="hobby in user.Hobbies">{{hobby}}</div>
</div>

In javascript :

 Object.defineProperty($scope, "searchFilter", {
            get: function () {
                var out = {};
                out[$scope.searchBy || "$"] = $scope.search;
                return out;
            }
        });

This is working only for Name column. For date column, there is a difference in format and as hobby is in inner loop, user is not displayed in the list even if the search text is in Hobbies. Can someone please help with a filter that satisfies all these values?

TIA.

1
any code where you tried to achieve this?ZombieChowder

1 Answers

0
votes

There are probably better solutions, but this might work:

JavaScript:

Object.defineProperty($scope, "searchFilter", {
  get: function () {
    var out = {};
    var search = $scope.search;
    if(!search) {
      return {'$': ''};
    }
    if($scope.searchBy === 'DoB') {
      search = new Date(search).getTime();
    }
    if($scope.searchBy === 'Hobbies') {
      $scope.users.forEach(function(n) {
        n.hobbyStr = n.Hobbies.join(',');
      });
      $scope.searchBy = 'hobbyStr';
    }
    out[$scope.searchBy || "$"] = search;
    return out;
  }
});

And here's a plnkr