Debug School

rakesh kumar
rakesh kumar

Posted on

Explain how to call api and renders to display data in angular js

Here's an example of how to display data in AngularJS using an API with the full code:

Define your API endpoint: In this example, we'll use the JSONPlaceholder API, which provides a set of fake JSON data for testing and prototyping. We'll use the /posts endpoint, which provides a list of posts.

Use AngularJS to make an HTTP request: In our AngularJS application, we'll use the $http service to make a GET request to the JSONPlaceholder API endpoint. We'll store the response data in the $scope.posts variable.

Render the data in your web application: We'll use the ng-repeat directive to iterate over the list of posts stored in the $scope.posts variable, and display the title and body of each post.

Here's the full code:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
  <meta charset="utf-8">
  <title>AngularJS API Example</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
</head>
<body ng-controller="myCtrl">
  <h1>AngularJS API Example</h1>
  <ul>
    <li ng-repeat="post in posts">
      <h2>{{ post.title }}</h2>
      <p>{{ post.body }}</p>
    </li>
  </ul>
  <script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $http) {
      $http.get('https://jsonplaceholder.typicode.com/posts')
        .then(function(response) {
          $scope.posts = response.data;
        });
    });
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

This code defines an AngularJS module called "myApp", and a controller called "myCtrl". In the controller, we use the $http service to make a GET request to the JSONPlaceholder API, and then store the response data in the $scope.posts variable. In the HTML, we use the ng-repeat directive to iterate over the list of posts stored in $scope.posts, and display the title and body of each post.

Top comments (0)