javascript - 如何在输入 AngularJS 时发送 GET 请求?

标签 javascript angularjs

我是 AngularJS 的新手。

我想对其进行设置,以便在输入时发送 GET 请求,但前提是我在 input 字段中输入的内容至少为三个字符长。

这是index.html:

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

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

但这似乎行不通。我该如何解决这个问题?

最佳答案

你必须为此使用 keyup 事件。

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

在你的 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);
    });
}

同时在您的 Controller 中注入(inject) $http

关于javascript - 如何在输入 AngularJS 时发送 GET 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29573847/

相关文章:

javascript - 如何过滤对象数组?

javascript - 创建 native JSON 数组时如何将其限制为最近 10 个

javascript - 使用 Hooks 在 React 中实现倒计时器

javascript - 获取文本小于 1024 个字符的 reddit 帖子

javascript - AngularJS - html select 的数据绑定(bind)默认值

angularjs - 如何通过拦截器向AngularJS中的http请求添加新的 header ?

javascript - 如何从图像 Canvas 中裁剪颜色部分?

javascript - 当我关闭模式时,选中的输入变为未选中状态

javascript - 如何在jquery中循环遍历ID

javascript - JSON.parse() 之后保留反斜杠