Search code examples
angularjsangular-filters

How to get the matching length from filter object?


I have a drop down, when user types on the input field, i am filtering the list according to the user what he types using the filter.

As well i would like to pick the length of the filtered list item from the filter object. how to get that?

example: if you type letter 'J' - my length should update as 3. because January, June and July all has letter 'J'

here is my code :

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.months = [
                "January", "February", "March", 
                "April", "May", "June", "July",  
                "August", "September", "October",
                "November", "December"
            ];

  $scope.defaultMonth = 'Select a Month';

  $scope.showList = false;

  $scope.setMonth = function ( month ) {
    $scope.defaultMonth = month;
    $scope.showList=false;
  }

});

here is the html :

 <form name="monthForm">
      <h2>Total Match : 0 </h2>
      <input 
        type="text" 
        name="selectMonth" 
        id="selectMonth" 
        ng-model="defaultMonth"
        ng-focus="showList=true"
        ng-pattern="{{ month }}"
        required>
      <span ng-show="monthForm.selectMonth.$error.required">Please enter something!</span>
      <div>
        <ul ng-show="showList" ng-onmouseover="showList=true">
          <li ng-repeat="month in months | filter:defaultMonth" ng-click="setMonth(month)">{{month}}</li>
        </ul>
      </div>
      <input type="button" ng-disabled="monthForm.$invalid" value="Submit">
    </form>

Live Demo ( please clear the input field and type in that )


Solution

  • Hold filtered list in a variable

    Like this

    ng-repeat="month in filtered=(months | filter:defaultMonth)"
    

    Then print the length of that variable

    Like this

    {{filtered.length}}
    

    PLUNKR