【问题标题】:$http get shortcut messing up program in AngularJS?$http 在 AngularJS 中获取快捷方式搞乱程序?
【发布时间】:2017-08-12 17:11:00
【问题描述】:

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

脚本循环遍历 $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)完全无关。完整的循环停止工作。

我是否遗漏了一些明显的东西?

【问题讨论】:

    标签: angularjs http angularjs-http


    【解决方案1】:
     app.controller("usercontroller", function($scope){  
    

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

    在函数参数中添加$http:

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

    我创建了一个 sn-p,这似乎现在可以工作

    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>

    【讨论】:

      猜你喜欢
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-14
      • 2017-06-09
      相关资源
      最近更新 更多