Nick Audenaerde Nick Audenaerde - 4 months ago 8
AngularJS Question

Cannot read property 'toLowerCase' of undefined angularjs

I'm trying to make a search function in my angularjs "webapp". When I search in products all works fine, but when I change everything so that it searches into users, i get an error Cannot read property 'toLowerCase' of undefined.

Here's my js:

return function(arr, searchString){
if(!searchString){
return arr;
}
var result = [];
searchString = searchString.toLowerCase();
angular.forEach(arr, function(item){
if(item.title.toLowerCase().indexOf(searchString) !== -1){
result.push(item);
}
});
return result;
};
});


And here's the html that's calling it:

<div ng-controller="userCtrl" class="container-app">
<div class="bar">
<input type="text" class="search" ng-model="searchString" placeholder="Enter your search terms" />
</div>
<div class="searchResultsText">
<h2>Zoekresultaten: </h2>
</div>
<div class="searchResults" ng-repeat="user in users | searchFor:searchString">
<a class="normal" href="#">{{user.name}}</a>
</div>




it does show me the list of users, just as soon as I start typing in the search bar it gives me the error.

when I use the exact same function, with a different controller it works. Here are the 2 controllers:

app.controller('customersCtrl', function ($scope, $http) {
$http.get(apiUrl + "product/list")
.success(function (response) {
$scope.products = response;
});
});

app.controller('userCtrl', function ($scope, $http) {
$http.get(apiUrl + "user/list")
.success(function (response) {
$scope.users = response;
});
});


so basically customerCtrl works fine, but when i change values to userCtrl it stops working.

any suggestions?

Answer

Most likely item.title is at least once undefined.

return function(arr, searchString){
    if(!searchString){
        return arr;
    }
    var result = [];
    searchString = searchString.toLowerCase();
    angular.forEach(arr, function(item){
        if(
            angular.isDefined(item.title) && 
            item.title.toLowerCase().indexOf(searchString) !== -1
        ){
            result.push(item);
        }
    });
    return result;
};