skip to Main Content

I want to use filter function and input search at the same time by using AngularJS. I can able to do with multiple functions. But I’m getting some errors while I add an textbox for search. Is there any way to do this? I tried some ways but no one did not work.

Thanks in advance.

Example code is below

var app = angular.module("app", []),
  url = "http://www.filltext.com/?rows=50&pretty=true&fName={firstName}&age=[18,19,20,21]";

app.controller("controller", function($scope, $http) {

  $http.get(url)
    .success(function(resp) {
      $scope.list = resp;
    });

  $scope.filterAge = function(item) {
    return item.age > 19;
  };

});
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://code.jquery.com/jquery.min.js"></script>
  <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
  <meta charset="utf-8">
  <title>AngularJS Filter</title>
</head>

<body ng-controller="controller">
  <div class="container">
    <br>
    <input type="text" ng-model="search" placeholder="Search..." />
    <table class="table table-striped">
      <thead>
        <th>Name</th>
        <th>Age</th>
      </thead>
      <tbody>
        <tr ng-repeat="item in list | filter: filterAge">
          <td>{{ item.fName }}</td>
          <td>{{ item.age }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</body>

</html>

2

Answers


  1.  $scope.$watch('search', function (data) {
        //sorting logic
    })
    

    Watcher is waiting for any action taken on search filed then the function is executed.

    Login or Signup to reply.
  2. You should add custom filter to angular module instead adding filter function to your controller. This is the example:

    CustomFilter:

    .filter('filterByAge', function filterByAge() {
      return function(array, age) {
        var filteredArray = [];
    
        angular.forEach(array, function(item) {
          if (item.age > age) {
            filteredArray.push(item);
          }
        });
    
        return filteredArray;
      }
    });
    

    HTML

    <input type="text" ng-model="search" placeholder="Search..." />
    <table class="table table-striped">
      <thead>
        <th>Name</th>
        <th>Age</th>
      </thead>
      <tbody>
        <tr ng-repeat="item in list | filter: search | filterByAge:19">
          <td>{{ item.fName }}</td>
          <td>{{ item.age }}</td>
        </tr>
      </tbody>
    </table>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search