【问题标题】:Make get calls in angular js after a small time of key up event在一小段按键事件后,在 Angular js 中进行 get 调用
【发布时间】:2025-12-23 07:55:11
【问题描述】:

我是 angular js 的初学者,在我的应用程序中,我使用了一个 web api,它提供了我们输入 pincode 时的位置。我在文本字段的 keyup 事件上调用我的控制器中的一个函数,但它会引发一些错误,并且有时不会使 get 调用正确。有没有办法解决这个问题?,我真正需要的是,只有当用户停止或等待在文本字段中输入下一个键时才进行 api 调用

HTML

<input type="text" ng-keyup="check();" ng-model="place" placeholder="Enter a pincode"/>
    <p>{{data.city}}</p>

Controller.js

app.controller('MyController', function($scope,$http) {

    $scope.check = function(){
    var req = {
         method: 'GET',
         url: 'https://sphirelabs-indian-pin-codes.p.mashape.com/pincode.php?code='+$scope.place,
         headers: {
            "Key": "api key",
            "Accept": "application/json"
         },
        }

    $http(req).
          success(function(data, status, headers, config) {
            $scope.data =  data;
          }).
          error(function(data, status, headers, config) {
            conosole.log("Error");
          })



    };


});

【问题讨论】:

    标签: javascript angularjs get timeout angular-http


    【解决方案1】:

    不要使用ng-keyup 事件。只需将您的输入包装在表单中,并在使用ng-submit 发送此表单时调用check() 函数:

    <form ng-submit="check()">
        <input type="text" ng-model="place" placeholder="Enter a pincode"/>
    </form>
    <p>{{data.city}}</p>
    

    所以当你在输入框中输入密码并按下回车键时,check() 函数将被调用。

    【讨论】: