Username Username - 7 months ago 14
Javascript Question

How do I send a GET request while typing in AngularJS?

I'm new to AngularJS.

I want to set it up so that as I type, I send a GET request, but only if what I've typed in the

input
field is at least three characters long.

Here's
index.html
:

<html ng-app="myApp">
<div ng-controller="fetchTagsCtrl">
<input type="text" ng-model="userInput.fetchTag" placeholder="Type something">
</div>
</html>


My Javascript:

var app = angular.module('myApp',[]);
app.controller('fetchTagsCtrl',function($scope){
$scope.userInput = {
fetchTag: ''
};

$http({
url: '/myURL',
method: 'GET',
param: {
someParameter: $scope.userInput
}
}).success(function(response){
console.log(response);
})
});


But this doesn't seem to work. How do I fix this?

Answer

You must use keyup event for that.

<input type="text" ng-model="userInput.fetchTag" ng-keyup="fetchdata()" placeholder="Type something">

In your controller:

$scope.fetchdata = function() {
  // condition to check for characters greater than 3.
  if($scope.userInput.fetchTag.length < 4) return;
  $http({
        url: '/myURL',
        method: 'GET',
        params : {
            someParameter: $scope.userInput
        }
    }).success(function(response){
        console.log(response);
    });
}

Also inject $http in your controller.

Comments