Last Updated: September 09, 2019
·
10.75K
· craigh_r

AngularJS live search

HTML input field

<input type="text" ng-model="searchText" ng-change="change(text)" placeholder="filter" />

Angular Controller

The $scope.change part will be called anytime the input field data is changed (Add, remove e.t.c.)
valtosend is the incoming data entered into the input field

App.controller('MainController', function($scope, $http, $timeout) {
    $scope.searchText = null;
    $scope.change = function(text) {
        valtosend = $scope.searchText;
        $http.get('http://website/getdatafunction/' + valtosend).then(function(result){
            $scope.entries = result.data;
        });
        };
    });

Returned data

My getdatafunction function is PHP, MySQL and Codeigniter you can obviously use your own for this.

I apply the obvious safety features to negate naughty input and then fetch the info from the database and echo out the returned data as

echo json_encode($query);

Back on the main page under the input field I have my list awaiting data being returned
It then loops through any returned data and displays on screen

<li ng-repeat="entry in entries">
<span class="{{entry.classname}}"><a href="{{entry.link}}">{{entry.title}} - {{entry.info}}</a></span>
</li>

My $scope.change fires off 5 x getdatafunction functions
In each one i amend entries part of this

$scope.entries = result.data;

to another variable name that is then waiting in another li
i.e

$scope.change = function(text) {
valtosend = $scope.searchText;
$http.get('http://website/getdatafunction/' + valtosend).then(function(result){
$scope.entries = result.data;
});
$http.get('http://website/getdatafunction/' + valtosend).then(function(result){
$scope.persons = result.data;
});

repeat  x 3 more
 };


<li ng-repeat="entry in entries">
<span class="{{entry.classname}}"><a href="{{entry.link}}">{{entry.title}} - {{entry.info}}</a></span>
</li>
<li ng-repeat="person in persons">
<span class="{{person.classname}}"><a href="{{entry.link}}">{{person.name}} - {{person.jobtitle}}</a></span>
</li>

there will be a better way of retrieving 5 sets of data from one input field, but I thought I would share my way!

1 Response
Add your response

Thanks, a great start!

over 1 year ago ·