Search code examples
angularjsangularjs-directiveangularangularjs-scope

angular global search only works without filter


I have a global search and it works only if I show the data as its in the controller. But as soon as I apply a filter, the search does not find it.

So if I have a date timestamp like 1429138800 and I have this in view

{{ date }}

it will work

But when I add a filter to show shortdate like this {{date | date:'shortDate'}} and I try to search for 1/17 it wont work.... how can I make it searchable after applying filters?


Solution

  • Well, I don't know about how you implement your filter, but for making instance of your filtered data you can do this:

    {{newDate = (date | date:'shortDate')}} -> "1/17"
    {{newDate}} -> "1/17"
    

    So now you can search your keyword in newDate instead of date.
    Hope to help!

    Update:
    Or maybe you can write a custom filter and convert your data before repeating on them without harming your main data:

    app.filter('toDate', ['$filter', function ($filter) {
        return function (a) {
          var b = angular.copy(a);
          for (var i=0, j=b.length; i<j; i++) {
            b[i] = $filter('date')(b[i], 'shortDate');
          }
          return b;
        }
    }]);
    

    And then use it like this:

    <ul>
       <li ng-repeat="item in dates | toDate | filter:key">{{item}}</li>
    </ul>
    

    angular.module("app", [])
    .controller("bodyCtrl", ["$scope", function($scope) {
      $scope.dates = [
        new Date("2016/1/1").getTime(),
        new Date("2016/1/2").getTime(),
        new Date("2016/1/3").getTime(),
        new Date("2016/1/4").getTime(),
        new Date("2016/1/5").getTime(),
        ]
    }])
    .filter('toDate', ['$filter', function ($filter) {
        return function (a) {
          var b = angular.copy(a);
          for (var i=0, j=b.length; i<j; i++) {
            b[i] = $filter('date')(b[i], 'shortDate');
          }
          return b;
        }
    }]);
    <!DOCTYPE html>
    <html ng-app="app">
    
      <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js"></script>
        <link rel="stylesheet" href="style.css" />
        <script src="script.js"></script>
      </head>
    
      <body ng-controller="bodyCtrl">
        <input type="text" ng-model="key">
        <hr>
        Without toDate Filter
        <ul>
          <li ng-repeat="item in dates | filter:key">{{item | date:"shortDate"}}</li>
        </ul>
        <hr>
        With toDate Filter
        <ul>
          <li ng-repeat="item in dates | toDate | filter:key">{{item}}</li>
        </ul>
      </body>
    
    </html>