Minimal AngularJS with http get example

Your script file should have the following contents:

(function() {
  var app = angular.module("SimpleAngularApp", []);

  var MainController = function($scope, $http) {

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

    var onError = function(reason) {
      $scope.error = "Could not fetch the user";
    }

    $http.get('https://api.github.com/users/berendjdejong')
      .then(onUserComplete, onError);
  };

  app.controller("MainController", ["$scope", "$http", MainController]);

}());

Then for your html file, which should include the script above and the Angular.js script, the contents should be:




  
    
    
    
  

  
    

{{user.login}}

{{error}}

Some important things to note:

  • The html tag contains an attribute with the name of your angular module SimpleAngularApp
  • The anonymous function is called immediately with a so called IIFE to setup the controller
  • The body tag has an attribute ng-controller that references the controller added to the module
Share

Leave a Reply

Your email address will not be published. Required fields are marked *