Aijaz Aijaz - 4 months ago 14
AngularJS Question

How to get back an array of objects which have a particular value using filters in AngularJS?

var foo = [
{
"id": 12,
"name": "Test"
},
{
"id": 2,
"name": "Beispiel"
},
{
"id": 3,
"name": "Sample"
},
{
"id": 4,
"name": "Test"
},
{
"id": 5,
"name": "Sample value"
},
{
"id": 6,
"name": "Testvalue"
}
];


I am trying to get a simple search input, which shows a couple of listings on ng-repeat. The search is basically a filter which shows searched items in that listing. What I have achieved is when I search something, with $http, it gets back the whole list of foo, and within that it filters. How can I just get the data with my keyword, and the whole JSON? For example if I search sample, how can I get the objects of id 3 and 5 so that I can display a new set of listings, or if I search with ID number 12, I get the object which has id as 12. The search term will be dynamic. I will be giving a $http call on every search as well.

Thanks.

Answer

If I understood well, it should work:

(function() {
  angular
    .module('app', [])
    .controller('MainCtrl', MainCtrl);

  MainCtrl.$inject = ['$scope', '$http'];

  function MainCtrl($scope, $http) {
    $scope.foo = [  
       {  
          "id":12,
          "name":"Test"
       },
       {  
          "id":2,
          "name":"Beispiel"
       },
       {  
          "id":3,
          "name":"Sample"
       },
       {  
          "id":4,
          "name":"Test"
       },
       {  
          "id":5,
          "name":"Sample value"
       },
       {  
          "id":6,
          "name":"Testvalue"
       }
    ];
  }
})();
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>

<body ng-controller="MainCtrl">
  <input type="text" ng-model="search" placeholder="Search">
  <ul>
    <li ng-repeat="item in foo | filter: search">
      <span ng-bind-template="{{item.id}} - {{item.name}}"></span>
    </li>
  </ul>
</body>

</html>

Note: If you want to perform a $http request based on search input, look at this DEMO.

Comments