subhra subhra - 4 months ago 28
AngularJS Question

Error in custom filter

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


Error:


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>
<td>{{cus.rest_name}}</td>
</tr>
</tbody>


My controller side code is given below.

customerView.filter('startsWithLetter', function () {
return function (items, letter) {
//console.log('items',items);
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))) {
filtered.push(item);
}
}
return filtered;
};
});
customerView.controller('adminCustomerViewController',function($scope,$state,$http,$window,$timeout,Upload,focusInputField){
$http({
method:'GET',
url:"php/customerInfo.php?action=disp",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
console.log('res',response.data);
$scope.listOfCustomerData=response.data;
},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(
i.e-rest_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
a
inside the search box the names started with a should filter . I did something but got the above error.Please help me.

Answer

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 = [  
       {  
          "name":"USA"
       },
       {  
          "name":"Japan"
       },
       {  
          "name":"France"
       },
       {  
          "name":"Canada"
       },
       {  
          "name":"China"
       }
    ];
  })

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

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

<body ng-controller="mainCtrl">
  <label for="letter">Filter: </label>
  <input type="text" id="letter" ng-model="letter">
  <hr>
  <table>
    <thead>
      <tr>
        <th>Name</th>
      </tr>
     </thead>
     <tbody>
      <tr ng-repeat="country in countries | startsWith: letter">
        <td ng-bind="country.name"></td>
      </tr>
     </tbody>
  </table>
</body>

</html>