跟踪用户输入并提供单词完成角度

时间:2016-04-25 08:39:54

标签: javascript php angularjs ajax

我是棱角分明的新人,我需要一些帮助。 假设我有一个包含数字列表的数据库,我想使用此列表来完成单词。

假设这是我的表格:

gen_cpp.sh

当用户插入至少5个字符时,我想对cd进行ajax调用以检索商品并显示它们。

请注意,ajax调用是在提交表单之前

php代码正在运行......我被困在客户端。

我知道我应该这样做:

          <!-- FORM -->
          <form>

                <!-- CODE -->
                  <label>code</label>
                  <input type="text" name="codeInput" placeholder="please insert your code..." >

                <!-- SUBMIT BUTTON -->
                <button type="submit" >Submit
                </button>
         </form>

我无法弄清楚如何连接所有组件。

2 个答案:

答案 0 :(得分:1)

On OliverJ90's answer there should be a small change. Do this in your html:

<form>
<!-- CODE -->
    <label>code</label>
    <input type="text" name="codeInput" placeholder="please insert your code..." ng-model="someValue" ng-change="myFunc()" >
    <!-- SUBMIT BUTTON -->
    <button type="submit" >Submit</button>
</form>

And then your javascript will be like this

$scope.myFunc = function(){
    //Do the following if $scope.someValue.length >= 5
    $http({
        method  : 'POST',
        url     : 'offers.php',
        data    : $scope.someValue,  
        headers : { 'Content-Type': 'application/x-www-form-urlencoded' } 
    }).success(function(data) {
           //display the data somehow...
    });
}

Basically someValue variable will provide a two way data-binding to your input box. that is, if someone changes value in text box, the variable value will change, and if someone changes variable value, input box value will change. This is the reason we have used ng-model. ng-change is just like calling a function on change event, but this is provided by angular.

Please note that, ng-change reuires ng-model, without which it will not work.

答案 1 :(得分:-1)

Method 1:

Bind to the input element:

<input ng-model="yourValue">

And in the controller watch for changes on yourValue

$scope.$watch(yourValue, function () {
   //check length and call your function that makes the http request.
});

Method 2:

Use ng-change

<input ng-change="checkValue()" ng-model="yourValue">

In your controller:

$scope.checkValue = function () {
  //do what you need to do.
}