Prash Prash - 5 months ago 12
AngularJS Question

Cannot access http json service in angular js

I am new to angularjs and I want to know why it isn't working.

The code has a flaw and am not sure about the same.

Thinking from java perspective,httpController defined has nested function defined inside.

Here it is my code

index.html

<!DOCTYPE html>
<html >

<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>

<body>
<div ng-app="myapp" ng-controller="HelloController">
<h2>{{message}}</h2>
</div>
<div ng-app="httpService" ng-controller="httpController">
<div>FirstName:{{user.name}}</div>
</div>
</body>

</html>


Script.js

var app = angular.module("myapp", []);
app.controller("HelloController", function($scope) {
$scope.message = "Hello, AngularJS";
});

var httpApp=angular.module("httpService",[]);

httpApp.controller("httpController",function($scope,$http){

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

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

}
);

Answer

Only one ng-app will be automatically bootstrapped on your page. That's why if you remove the first ngApp directive, the second one will work.

var httpApp = angular.module("httpService", []);

httpApp.controller("httpController", function($scope, $http) {

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

  $http.get("https://api.github.com/users/rob").then(onUserComplete);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>

<div ng-app="httpService" ng-controller="httpController">
  <div>FirstName: {{user.name}}</div>
</div>

NOTE: You have a typo in your callback, remove ""s around your response.data. Also, since you are using Angular 1.5.6, you don't need to specify dependencies/inject your $http service to make your code work.