Issue with Ionic displaying data from AngularJS $http.get request

Having just started learning AngularJS, I have followed tutorials on YouTube and read the documentation, but I am struggling to display data from an API using the $http.get() request.

Here is my JavaScript and HTML code:

var exampleApp= angular.module('app', ['ionic']);

exampleApp.controller('exampleController', function($scope, $http){
  
  $scope.getData=function(){
      $http.get("https://p3ddibjuc6.execute-api.us-west-2.amazonaws.com/prod/entries")
    .success(function(data){
      $scope.Date= data.Date;
      $scope.message= data.message;
    })
    .error(function(data){
      alert("error");
    })
  };
} );
!DOCTYPE html>
<html ng-app="app">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <link href="https://code.ionicframework.com/1.0.0/css/ionic.min.css" rel="stylesheet">
    <script src="https://code.ionicframework.com/1.0.0/js/ionic.bundle.js"></script>
  </head>
  <body ng-app="app">
    <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title">Awesome App</h1>
      </ion-header-bar>
      <ion-content class="padding" ng-controller="exampleController">
        <button class="button button-assertive" ng-click="getData()">click</button>
        <br>
        MESSAGE: {{message}}
        <br>
        Date: {{Date}}
      </ion-content>
    </ion-pane>
  </body>
</html>

enter code here

Answer №1

var exampleApp= angular.module('app', ['ionic']);

exampleApp.controller('exampleController', function($scope, $http){

  $scope.fetchData=function(){
      $http.get("https://p3ddibjuc6.execute-api.us-west-2.amazonaws.com/prod/entries")
    .then(function(response){
      var data = response.data;
      $scope.Date= data.items[0].Date;
      $scope.message= data.items[0].message;

//for looping through data items
      $scope.info = data.items;
    })
    .catch(function(response){
      alert("error");
    })
  };
});

To access the first Date and Message or all entries, you can use ng-repeat in your HTML to iterate over the API data.

In your HTML:

<div ng-repeat="item in info"> 
Date: {{item.Date}}
message: {{item.message}}
</div>

Answer №2

Utilize the ng-repeat directive to display a list of information:

<div ng-repeat="item in Items"> 
      Date: {{item.Date | date}}
    <br>
      MESSAGE: {{item.message}}
  </div>

The methods .success and .error are no longer supported. Instead, use .then and .catch:

$http.get(url)
    .then(function(response){
      var data = response.data;
      $scope.Items = data.Items;
  })
    .catch(function(response){
      console.log("error: ",response.status);
  })

The DEMO

angular.module('app', ['ionic'])

.controller('exampleController', function($scope, $http){
  $scope.getData=function(){
    var url = "https://p3ddibjuc6.execute-api.us-west-2.amazonaws.com/prod/entries"
    $http.get(url)
    .then(function(response){
      var data = response.data;
      $scope.Items = data.Items;
    })
    .catch(function(response){
      console.log("error");
    })
  };
});
<!DOCTYPE html>
<html ng-app="app">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <link href="//unpkg.com/ionic-sdk/release/css/ionic.min.css" rel="stylesheet">
    <script src="//unpkg.com/ionic-sdk/release/js/ionic.bundle.js"></script>
  </head>
  <body ng-app="app">
    <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title">Awesome App</h1>
      </ion-header-bar>
      <ion-content class="padding" ng-controller="exampleController">
        <button class="button button-assertive" ng-click="getData()">click</button>
        <br>
        <div ng-repeat="item in Items"> 
          Date: {{item.Date | date}}
        <br>
          MESSAGE: {{item.message}}
        </div>
      </ion-content>
    </ion-pane>
  </body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps do I need to take to retrieve the passed slug in my API (slug=${params.slug})?

Is there a way for me to retrieve the passed slug in my API (slug=${params.slug}) while using the vercel AI SDK? const { messages, input, handleInputChange, handleSubmit, isLoading, error } = useChat({ api: `/api/conversation?slug=${params.slug ...

Is it possible to apply CSS based on a component's displayName?

Are you a CSS pro? I'm attempting to apply a class that will make all descendants of an element read-only, but for some reason the style isn't being applied as expected: #ComponentDisplayName * { -webkit-user-select: text; -moz-user-sel ...

Target the most recently loaded Vue.js element using jQuery's focus method

Hey there, I am currently utilizing Vue.js to load some data and below is the code snippet: add_line:function() { index = this.lines.length; this.lines.push({id:index}); $('.search_and_select').last().focus(); ...

Struggling to make ng-repeat function properly within an AngularJS controller when working with arrays

I am having trouble with my code. The ng-repeat in my AngularJS app is displaying blank. Can someone help me figure out why? Thanks in advance, Stephanie <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/aja ...

What is the best way to save a webpage when a user clicks a button before leaving the page with Javascript

I've exhausted all my options in trying to find a way to trigger a button that saves the page upon exit, but it never seems to work. I need the event to occur even if the button is not visible at the time of the page exit. The new security protocols o ...

Using jQuery, remove any white spaces in a textbox that are copied and pasted

There is a textbox for entering order IDs, consisting of 7 digits. Often, when copying and pasting from an email, extra white spaces are unintentionally included leading to validation errors. I am looking for a jQuery script to be implemented in my Layout ...

The robots.txt file in Nuxt.js allows for multiple disallow directives for each user agent

With the Nuxt module called nuxt-robots, how can I set up multiple disallow rules per user agent? Currently, my configuration looks like this: robots: () => { return { UserAgent: '*', Disallow: '/search/', Si ...

Utilizing vuetifyjs: Selectively incorporating necessary icons into the build

I am currently working on a vuetifyjs-app using the default "Material Design Icons". For the production build, I am only utilizing 2 icons from this font (which are being used by the vuetify-component chips). Following recommendations, I have included the ...

Latest Information Regarding Mongodb Aggregate Operations

Struggling to toggle a boolean value within an object that is part of a subdocument in an array. Finding it difficult to update a specific object within the array. Document: "_id" : ObjectId("54afaabd88694dc019d3b628") "Invitation" : [ { "__ ...

Transforming text colors dynamically using Vue.js

Here is an Angular code snippet: <div [style.color]="'#' + prod.id.substring(0,6)"> <small>{{ prod.id }}</small> </div> Now I want to create a similar code using vue.js. ...

Having trouble with JavaScript concat function not behaving as it should? Can you provide more details to

I am trying to extract all the cities from an object that contains country names as keys and arrays of cities as values. However, my approach seems to be failing and I can't figure out why. var cities = { "United Kingdom": ['london'], ...

Executing a function in JavaScript using square brackets

While I was reading through the jQuery source code, I came across this interesting line: jQuery(this)[ state ? "show" : "hide" ](); Is there any particular benefit to using this syntax over the more traditional approach shown below? state ? jQuery(this) ...

When using a file uploader to set an image on v-model in Vue JS, it sometimes results in

I am currently using Vue JS 2 to develop an image uploader functionality. The input in question has a change function that triggers a function and sets the selected file to the v-model property. After logging the data, I noticed that only an empty object ...

What about nested elements with percentages, set positions, and fixed placements?

Picture: I am working on a design with a yellow container div that I want to keep at 50% width of the window. Inside this container is a purple image div that stretches to 100% of the parent container's width, and there is a pink sticky label positi ...

Total Output Calculation

In my latest coding project, I have crafted a unique algorithm to calculate exam scores with the inclusion of interactive buttons! function incorrectResponse() { var calc = 0; var calc2 = 1; var divElement = document.createElement("div"); divEle ...

Cannot chain promises using 'then'

Having trouble understanding why the 'describeDir' promise chain is not working properly. Can anyone help me figure out what I did wrong here? Everything in the code seems to run, but functions like then or finally from the promise API never get ...

Is Typescript familiar with the import -> require syntax, but unfamiliar with the require -> import syntax?

My code includes a simple file that utilizes the ES6 module loader: 1.ts import {foo} from "./2" foo('hello'); 2.ts function foo (a){console.log(a);}; export {foo} When the tsconfig is configured as follows: "module": "commonjs", We can o ...

Attempting to load using ajax, Chrome and jquery-mobile will modify the location of the window through setting window.location.href

I'm encountering a challenge with my mobile application where I need to redirect users to the login page on a 401 ajax call. However, it seems that jQM is attempting to load this via AJAX when the request is sent. This solution works flawlessly for s ...

Using JavaScript, the list of items (images) will be displayed and placed into HTML panels

Below is the layout structure on my website: <div class="panel-heading"><h3 class="panel-title">Suggestions</h3></div> <div class="panel-body"> <div class="col-md-7"> <h3><span class= ...

React Hooks: In useEffect(), unable to modify parent component's state

Within my component, I have a form for users to input a title, description, and images. This component is nested within its parent component, and I want the form data to be saved if the user switches sections and returns later without losing their progress ...