我如何在AngularJS中调用$ http.get

时间:2018-07-28 11:38:11

标签: angularjs

尝试学习angularjs,因为我需要在工作中修改一些东西,而这正是他们正在使用的东西,目前我无法升级到Angular2 +。我在尝试使用$ http.get方法但在控制台中得到$ http notdefined error的地方有以下代码。

// js代码

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

app.controller('HelloWorldCtrl', function($scope){

  var onUserComplete = function(response){
    $scope.user = response.data;
  };

  $http.get("https://api.github.com/users/robconery")
      .then(onUserComplete);

  $scope.message = "Hello, AngularJS";
});

// HTML

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <script data-require="angular.js@*" data-semver="4.0.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.10/angular.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="HelloWorldCtrl">

    <h1>{{message}}</h1>

    <div>
      Name: {{user.name}}
    </div>
    <div>
      Location: {{user.location}}
    </div>

  </body>

</html>

1 个答案:

答案 0 :(得分:1)

您需要将 $http 作为依赖项传递给控制器​​,

app.controller('HelloWorldCtrl', function($scope,$http){
});

演示

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

app.controller('HelloWorldCtrl', function($scope,$http){

  var onUserComplete = function(response){
    $scope.user = response.data;
  };

  $http.get("https://api.github.com/users/robconery")
      .then(onUserComplete);

  $scope.message = "Hello, AngularJS";
});
<!DOCTYPE html>
<html ng-app="app">

  <head>
    <script data-require="angular.js@*" data-semver="4.0.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.10/angular.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="HelloWorldCtrl">

    <h1>{{message}}</h1>

    <div>
      Name: {{user.name}}
    </div>
    <div>
      Location: {{user.location}}
    </div>

  </body>

</html>