如何在AngularJS中键入时发送GET请求?

时间:2015-04-11 03:41:35

标签: 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);
    })
});

但这似乎不起作用。我该如何解决这个问题?

4 个答案:

答案 0 :(得分:5)

您必须使用keyup事件。

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

在您的控制器中:

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

同时在控制器中注入$http

答案 1 :(得分:3)

你的html dom是对的。只需简单地改变你的脚本即可。按照下面提供的步骤进行操作

第1步: 将$ http注入您的控制器  例如:app.controller(&#39; fetchTagsCtrl&#39;,函数($ scope,$ http)

第2步: 使用$ scope。$ watch从输入中获取您的输入事件

让我们看看下面的代码将会是

var app = angular.module('myApp',[]);
app.controller('fetchTagsCtrl',function($scope,$http){
$scope.userInput = {
    fetchTag: ''
};
$scope.$watch('userInput.fetchTag',function(){
    $http({
        url: '/myURL',
        method: 'GET',
        param: {
            someParameter: $scope.userInput
        }
    }).success(function(response){
        console.log(response);
     })
    });
});

答案 2 :(得分:2)

您可以使用ng-change指令而不是ng-keyup。因为输入中的每次更改都会调用控制器中的fetchdata方法。

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

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

答案 3 :(得分:1)

观察模型的变化,进行检查,然后触发您的请求。以下是我的写作方式:

app.controller('fetchTagsCtrl',function($scope){
    $scope.userInput = {
        fetchTag: ''
    };;

    $scope.$watch('userInput.fetchTag',function(value){
        if(value.length >= 3){
            makeRequest();
        }
    });

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