0

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;
    });


  }]);

2 Answers 2

4

You must do this:

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

it's all.

Sign up to request clarification or add additional context in comments.

Comments

0

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;
});
}]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.