Category Archives: JavaScript

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

Immediately invoked function expression IIFE

Below is a code snippet for a Immediately invoked function expression IIFE. An IIFE is used to keep code out of the global namespace.

(function() {
  var createWorker = function() {
    
    var workerCount = 0;

    var task = function() {
      workerCount += 1;
      console.log("task " + workerCount);
    };

    return {
      task: task
    };
  };
  
  var prg = createWorker();
  
  prg.task();
  
}());
Share