自动请求

时间:2016-08-05 04:07:04

标签: angularjs rest input service

我正在开发angularJS。

我有一个输入连接到服务邮政编码的服务。 (在我的情况下,所有的邮政编码都有5个数字)

我希望当我输入第5个号码时,它会在没有按下按钮的情况下拨打电话。

我的服务是:

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;
        });
    };

}

我使用的是SendCP&#39;作为获得回应的触发器。

1 个答案:

答案 0 :(得分:2)

您可以对任何具有ng-model的输入使用ng-change,并且当由于用户事件(键入)更新模型时,ng-change将触发,在那里你可以检查是否有长度字符串匹配5,如果激活你的功能。

&#13;
&#13;
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();
  }
});
&#13;
<!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>
&#13;
&#13;
&#13;