Nagarjuna Reddy
Nagarjuna Reddy

Reputation: 4195

AngularJS filter from first letter (Like Google search)

I am writing the code in directive for searching (Using textbox). This is the code

+ "<input type='text'  class='form-control' ng-model='newrecord."
+ attribute.name
+ "' name='"
+ attribute.name
+ "'placeholder='Start typing patient name"
+"' typeahead='"
+"a.value as a.value for a in getpatients($viewValue) | limitTo:20:begin "
+"'/>"

This is my Controller code

 $scope.getpatients = function(queryString) {
            if (queryString == undefined || queryString.length < 0) {
                return [];
            }
            queryString = 'query={"patientName":"'+queryString+'"}';

The above code is working & I can able to search. But it is searching middle letters also. I want to search from the first letter of the word like Google. Help me.

Upvotes: 0

Views: 4235

Answers (2)

yazaki
yazaki

Reputation: 1632

In Angular-way, I recommend you to write simple custom filter code. I would expect what you want to achieve is something like this.

In html.

<div ng-app="myapp" ng-controller="myctrl">
    <input type="text" ng-model="filter_text">
    <ul>
        <li ng-repeat="item in items | myfilter:filter_text">
            {{item}}
        </li>
    </ul>
</div>

In javascript.

angular.module('myapp', []).filter('myfilter', function(){
    return function(input, text){
        // I recommend to use underscore lib for old browser.
        return input.filter(function(item){
            // I recommend to use standard regex for old browser.
            return item.startsWith(text);
        });
    };
});

function myctrl($scope){
    $scope.filter_text = 'a';
    $scope.items = [
        'abc',
        'bca'
    ];
}

I setup jsfiddle.

I hope this sample could help you.

Upvotes: 1

Mavlarn
Mavlarn

Reputation: 3883

I think it is about the function in your server side code. Maybe the search function in your server will search with like. If you can not modify server side code, maybe you can try to add regexp char for starting like '^'.

Upvotes: 0

Related Questions