Patricio Bustos Patricio Bustos - 4 months ago 23
reST (reStructuredText) Question

Do an automatic request

Im working on angularJS.

I have an input connected to a service who serves a postal code. (in my case all the zip codes have 5 numbers)

I want that when I put the 5th number, it makes the call without press a button.

My service is this:

angular
.module('myApp')
.controller('codPostal', codPostal);

function codPostal($scope, $http, $rootScope) {
$scope.SendCP = function () {
var config = {
headers : {
'Content-Type': 'application/json;charset=utf-8;'
}
}
$http({
method:'GET',
url:'https://postal-code.service.com/' + $scope.formData.domicilio.codPostal,

headers: {
'Content-Type': 'application/json'
}
})
.success(function ( data, status, headers, config) {
$rootScope.cpResponse = data;

})
.error(function (data, status, header, config) {
$scope.CPdetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
};


}

I use a 'SendCP' as trigger to get the response.

Answer

You can use ng-change on any input that has an ng-model and when the model is updated due to a user event (key up) the ng-change will fire, in there you can check if the length of the string matches 5 and if so fire your function.

angular.module('myApp',[])
.controller('myCtrl', function($scope){

  $scope.SendCP = function(){ alert('do existing thing here')}
  
  $scope.zipCodeHandler = function(zipcode){
    if(zipcode.length==5)
      $scope.SendCP();
  }
});
<!DOCTYPE html>
<html ng-app="myApp">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>

<body ng-controller="myCtrl">

  <input ng-model="zipCodeHere" ng-change="zipCodeHandler(zipCodeHere)"/>


</body>

</html>