subhra subhra - 1 year ago 97
AngularJS Question

Error in custom filter

I am getting the below error while using angular.js filter methos.


TypeError: Cannot read property 'length' of undefined
at adminCustomerViewController.js:1387
at fn (eval at compile (angularjs.js:212), <anonymous>:4:464)
at dirPagination.js:100
at Object.<anonymous> (angularjs.js:115)
at n.$digest (angularjs.js:130)
at n.$apply (angularjs.js:133)
at g (angularjs.js:87)
at K (angularjs.js:91)
at XMLHttpRequest.z.onload (angularjs.js:92)

I am explaining my code below.

<input class="form-control" placeholder="Type Restaurant Name" name="q" type="text" ng-model="letter">
<tr dir-paginate="cus in ($parent.labelResults=(listOfCustomerData | startsWithLetter:letter | orderBy:'rest_name')) | itemsPerPage:5 track by $index" current-page="currentPage">
<td>{{itemsPerPage *(currentPage-1)+$index+1}}</td>

My controller side code is given below.

customerView.filter('startsWithLetter', function () {
return function (items, letter) {
var filtered = [];
var letterMatch = new RegExp(letter, 'i');
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (letterMatch.test(item.rest_name.substring(0, 1))) {
return filtered;
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
},function errorCallback(response) {

Actually i am implementing the search functionality here . Here my requirement is when user will type at least first letter of the restaurant name(
) the related restaurant will filter from the table. Suppose i have many restaurant like
Anjum,A&P Chinese Food Express,Bookers BBQ & Crab Shack,Butcher And The Baker, Cactus Club Stephen Avenue,Cactus Club - Macleod Trail
. Here when user is typing only
inside the search box the names started with a should filter . I did something but got the above error.Please help me.

Answer Source

Since you want only those objects that have the corresponding letters to input you don't need to use Regexp.

Here a snippet working:

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

  .controller('mainCtrl', function($scope) {
    $scope.countries = [  

  .filter('startsWith', function() {
    return function(items, search) {
      if (!search) {
        return items;
      search = search.toLowerCase();
      return items.filter(function(element) {
        return, search.length).indexOf(search) != -1;
<!DOCTYPE html>
<html ng-app="app">

  <script src=""></script>

<body ng-controller="mainCtrl">
  <label for="letter">Filter: </label>
  <input type="text" id="letter" ng-model="letter">
      <tr ng-repeat="country in countries | startsWith: letter">
        <td ng-bind=""></td>


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download