membersound
membersound

Reputation: 86847

How to create a basic angularjs page for REST json data?

I'm trying to create a basic webpage that shows data retrieved by http://rest-service.guides.spring.io/greeting.

The json output is:

{"id":2273,"content":"Hello, World!"}

I'm using the following html page:

<body ng-app="hello">
    <div class="container">
        <h1>Greeting</h1>
        <div ng-controller="home" ng-cloak class="ng-cloak">
            <p>The Id is: {{greeting.id}}</p>
            <p>The content is: {{greeting.content}}</p>
        </div>
    </div>
    <script src="js/angular-bootstrap.js" type="text/javascript"></script>
    <script src="js/hello.js"></script>
</body>

And the hello.js:

var myApp = angular.module('hello', []);

myApp.controller('home', ['$scope', function($scope) {
    $scope.greeting = {};

    $http.get('http://rest-service.guides.spring.io/greeting')
        .success(function(data, status, headers, config) {
            $scope.greeting = data;
        });
}]);

Result: the placeholders greeting.id/content are not resolved. What might be wrong here?

Upvotes: 1

Views: 201

Answers (3)

akn
akn

Reputation: 3722

You didn't inject $http service.

myApp.controller('home', ['$scope, $http', function($scope, $http) {...}]);

EDIT

It is also worth to metnion what cverb said in his answer. In Angular 1.4 you should replace .success() with .then(), because .success is deprecated.

Now usage should be:

$http.get(url).then(
  function(data){
     //success callback
  }, 
  function(){
     //error callback
  });
);

Upvotes: 7

cverb
cverb

Reputation: 643

Change your .success() with .then(), the .success() method is deprecated and does not work in the same way as a normal promise.

If you wish to keep using it, you can just use it like this.

 $http.get('http://rest-service.guides.spring.io/greeting')
        .success(function(data) {
            $scope.greeting = data;
        });

Also see the documentation of $http.

Upvotes: 0

dhavalcengg
dhavalcengg

Reputation: 4713

change your $http call to following. You have also not injected $http in your controller.

 $http.get('http://rest-service.guides.spring.io/greeting')
        .success(function(data, status, headers, config) {
            $scope.greeting = data.data;
        });

Upvotes: 0

Related Questions