mediaguru
mediaguru

Reputation: 1917

AngularJS filter by specific item in array

I'm in Angular 1.4.8. I'm using a basic search filter to find a user. The search works, but is searching the whole data set. For instance searching below for "Mar" would find three results because one last name contains Mar. I would like to search only by first name. The ultimate goal is to find the number of records found: Result {{count}}. So searching for "St" should find ONE result, the first name Steve (not Stanford).

Here's a fiddle: http://jsfiddle.net/mediaguru/z5shgzxw/1/

  <div ng-app="myApp">
    <div ng-controller="MyCtrl">
      <input type="text" ng-model="search">
      <table>
        <tbody>
          <tr ng-repeat="item in items">
            <td>ID: {{item.id}}</td>
            <td>Name: {{item.firstname}}</td>
            <td>Gender: {{item.lastname}}</td>
          </tr>
        </tbody>
      </table>
      Result {{count}}
    </div>
  </div>

JS

  var myApp = angular.module('myApp', []);
  myApp.controller('MyCtrl', ['$scope', '$filter', function($scope, $filter) {


    $scope.items = [{
      id: 1,
      firstname: 'John',
      lastname: 'Jones'
    }, {
      id: 2,
      firstname: 'Steve',
      lastname: 'Jones'
    }, {
      id: 3,
      firstname: 'Joey',
      lastname: 'Maritza'
    }, {
      id: 4,
      firstname: 'Mary',
      lastname: 'Linqust'
    }, {
      id: 5,
      firstname: 'Marylin',
      lastname: 'Stanford'
    }];

    $scope.items2 = $scope.items;

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


  }]);

Upvotes: 0

Views: 244

Answers (2)

sameera lakshitha
sameera lakshitha

Reputation: 1971

You must write ($scope.items2, {firstname:val});

You can solve your problem by using below code.

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', '$filter', function($scope, $filter) {

$scope.items = [{ 
  id: 1,
  firstname: 'John',
  lastname: 'Jones'
}, {
  id: 2,
  firstname: 'Steve',
  lastname: 'Jones'
}, {
  id: 3,
  firstname: 'Joey',
  lastname: 'Maritza'
}, {
  id: 4,
  firstname: 'Mary',
  lastname: 'Linqust'
}, {
  id: 5,
  firstname: 'Marylin',
  lastname: 'Stanford'
}];

$scope.items2 = $scope.items;

$scope.$watch('search', function(val) {
  $scope.items = $filter('filter')($scope.items2, {firstname:val});
  $scope.count = $scope.items.length;
});
}]);

Upvotes: 0

Luis Machillanda
Luis Machillanda

Reputation: 111

You must do this:

$scope.items = $filter('filter')($scope.items2, {firstname:val});

it's all.

Upvotes: 4

Related Questions