rizzo
rizzo

Reputation: 39

How do I call $http.get in AngularJS

Attempting to learn angularjs because I need to modify some stuff at work and that is what they are using and I can't upgrade to Angular2+ at the moment. I have the following code where I'm trying to use the $http.get method but getting $http not defined error in the console.

// js code

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>

Upvotes: 2

Views: 1039

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222522

You need to pass $http as a dependency to your controller,

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

DEMO

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>

Upvotes: 1

Related Questions