$http 获取快捷方式搞乱 AngularJS 中的程序?

$http get shortcut messing up program in AngularJS?

在下面的脚本中,我发布了我的代码的简化版本。它本质上是一个简化的搜索引擎。

脚本遍历 $scope.list_of_fruit 数组,并根据在简单 html 输入文本框中键入的内容进行过滤。

 <script>  
 var app = angular.module("myapp",[]);  
 app.controller("usercontroller", function($scope){  
      $http
      .get("test.php")
      .then(function (response) {
          $scope.myData = response.data.records;
      });

      $scope.list_of_fruit = ["apple", "banana", "pear", "kiwi"];

      $scope.complete = function(boxtext){  
           var output = [];  
           angular.forEach($scope.list_of_fruit, function(fruit){  
                if(fruit.toLowerCase().indexOf(boxtext.toLowerCase()) == 0)  
                {  
                     output.push(fruit);  
                }  
           });  
           $scope.filteredfruit = output;  
      }  
 });  
 </script>  

这很好用,但当我将那个 http get 请求粘贴到顶部时,它完全不相关 到那个 $scope.complete 循环,$scope.complete 循环就停止工作了。

我是不是遗漏了什么明显的东西?

 app.controller("usercontroller", function($scope){  

您没有定义 $http,因此您可能收到 javascript 错误。

在函数参数中添加$http:

 app.controller("usercontroller", function($scope, $http){ 

我创建了一个片段,现在似乎可以使用了

var app = angular.module('myApp', []);

app.controller("usercontroller", function($scope, $http){  
      $http
      .get("https://jsonplaceholder.typicode.com/posts")
      .then(function (response) {
      $scope.myData = response.data.records;
      });

      $scope.list_of_fruit = ["apple", "banana", "pear", "kiwi"];

      $scope.complete = function(boxtext){  
           console.log(boxtext);
           var output = [];  
           angular.forEach($scope.list_of_fruit, function(fruit){  
                if(fruit.toLowerCase().indexOf(boxtext.toLowerCase()) == 0)  
                {  
                     output.push(fruit);  
                }  
           });  
           $scope.filteredfruit = output;  
      }  
 });  
<!DOCTYPE html>
<html ng-app='myApp'>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<script src="https://rawgit.com/angular/bower-angular/master/angular.min.js"></script>
  
  <div ng-controller="usercontroller as vm">
    {{list_of_fruit}}
    {{filteredfruit}}
    
    <input type="text" ng-model="search"/>
    <button ng-click="complete(search)">Do something</button>
    
  </div>

</body>
</html>