skipper skipper - 3 months ago 5
AngularJS Question

Javascript error trying to perform a search filter using Angular JS

In my app Im trying perform a search filter on names by partial match from the beginning. Heres an example of what Im trying to do:

Lets say I have a list of names:

Ben
James
Adam
Judy
Andy


and enter the text
"a"
in my search field, it would return

Adam
Andy


if I further enter
"an"
in my search field, it would return

Andy


In my app.js, I have the code:

var myApp = angular.module("myApp", []);

myApp.controller("myController", function ($scope) {
var employees = [
{ name: "Ben", gender: "Male", salary: 55000, city: "London" },
{ name: "Jane", gender: "Female", salary: 62000, city: "Albany" },
{ name: "Rick", gender: "Male", salary: 65000, city: "Los Angeles" },
{ name: "Pam", gender: "Female", salary: 60000, city: "Paris" },
{ name: "Josh", gender: "Male", salary: 68000, city: "Brussels" },
];

$scope.employees = employees;

$scope.filtered = function (item) {
if ($scope.searchName == undefined) {
return true;
} else {
if (item.name.toLowerCase().startsWith($scope.searchName.toLowerCase()) != -1) {
return true;
}
}

return false;
}
});


And in my html page, I have the following line which displays the list of employees:

<tr ng-repeat="employee in employees | filter: filtered">


And the following line which the user inputs the search text:

<input type="text" placeholder="Search Name" ng-model="searchName.name"> <br><br>


However, when I attempt to test this, I get the error:

Error: $scope.searchName.toLowerCase is not a function. (In '$scope.searchName.toLowerCase()', '$scope.searchName.toLowerCase' is undefined)

Answer

As your ng-model is set to searchName.name, $scope.searchNameis an object, therefore it has no .toLowerCase() function.

You need to adjust your if-case like this:

if (item.name.toLowerCase().startsWith($scope.searchName.name.toLowerCase()) !== -1) {}

Furthermore, it is advisable to use identity operators instead of equality operators, unless strict identity is explicitly not needed.

Comments