Prash
Prash

Reputation: 554

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);

}
);

Upvotes: 0

Views: 59

Answers (2)

Uzbekjon
Uzbekjon

Reputation: 11813

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.

Upvotes: 2

Pankaj Kumar
Pankaj Kumar

Reputation: 881

https://plnkr.co/edit/LyWCLeBeyHPzjys3LOcr?p=preview

<body ng-app="httpService">

    <div  ng-controller="httpController">
        <div>FirstName: {{user.key}}</div>
    </div>
</body>

This link is working fine...just try it out

Do not use ng-app more than once in your program...Your code would not work

Upvotes: 2

Related Questions