简体   繁体   中英

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

}
);

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM