0

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)

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I had the ng-model set to "searchName.name" because in that case, the default filter would only search the "name" columns and I assumed that I would need it the same for my custom filter.
1

The ng-model is set to searchName.name, so you may need to call on $scope.searchName.name.toLowerCase() instead of $scope.searchName.toLowerCase()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.