Retrieving information from a JSON document in IONIC with the help of AngularJS

Issue

After using the ionic tabs template to create my first project with the ionic framework, I noticed that the data for friends and friend details is being pulled from an array list in the services.js file. However, I would like to instead fetch this data from a JSON file hosted on a web server (e.g. ). How can I accomplish this?

Inquiry

What is the process for retrieving JSON data from a web server and incorporating it into my app?

Answer №1

Custom Factory in services.js

To begin, create a custom factory and replace the example URL with your own.

.factory('CustomData', function ($http, $rootScope, $stateParams) {

  return {
    all: function () {
      return $http.get('https://customdata.json/all', { params: { user_id: $rootScope.session } })
    },
    get: function () {
      return $http.get('https://customdata.json/getOne', { params: { user_id: $rootScope.session, chat_id: $stateParams.idchat } })
    },
    add: function (id) {
      return $http.get('https://customdata.json/new', { params: {id:id}})
    }
  };
});

Controller Configuration in controllers.js

Next, set up a controller to interact with the factory and retrieve data for use in the application.

.controller('CustomCtrl', function ($scope, CustomData) {

  CustomData.all().success(function (response) {
    $scope.customData = response;
  })
})

Binding Data to View Scope

Bind the retrieved data to the view scope so it can be displayed to the user.

Now, you can display the data in the view by accessing it through the $scope variable. Use this list to showcase the data obtained from the server with options to add or delete entries.

<ion-view view-title="Contacts">
  <ion-content>
  <ion-list>
      <ion-item class="item-icon-right" ng-repeat="item in customData">
          <h1>{{ item.username }}</h1>
          <p>{{ item.friendNumber}}</p>
          <i class="icon ion-chevron-left icon-accessory"></i>
          <ion-option-button class="button-positive" ng-click="viewFriend(viewFriend(item.id))">View Friend</ion-option-button>
          <ion-option-button class="button-assertive" ng-click="deleteFriend(remove(item.id))">Delete</ion-option-button>
      </ion-item>
    </ion-list>
  </ion-content>
</ion-view>

Note:

The code provided is based on an adaptation of existing code. While I haven't tested this exact version, the original code functions properly. For more details or the complete code, visit my GitHub repository https://github.com/joeLloyd/Scripto5000

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

How can we showcase an HTML file in Express by utilizing a POST request?

My objective is to successfully submit my form data and then dynamically navigate to an HTML file where the values are displayed. Here's the code snippet from my app.post function in Express: const results = fs.readFile("order.html", " ...

Retrieve all elements from an array using jQuery

How do I extract all the elements from the array outside of the function? $.each(Basepath.Templates, function(i){ templateArray = new Array({title: Basepath.Templates[i].Template.name, src: 'view/'+Basepath.Templates[i].Template.id, descri ...

Is the user currently browsing the 'Home screen webpage' or using the Safari browser?

In JavaScript, is there a method to determine if the user has accessed the website from their home screen after adding it to their home screen, or if they are browsing via Safari as usual? ...

Adjust the size of the font in your Bootstrap Table

I've been utilizing the Bootstrap table feature and it's been fantastic, but I've encountered an issue with changing the font size. I've referred to the example on , however no matter what adjustments I make to the size, it doesn' ...

Updating an array element in Mongoose, the MongoDB ORM

I am currently in the process of making changes to a MongoDb collection that contains an array of documents called items. To achieve this, I am utilizing the express and mongoose frameworks. This is how my schema is structured: const mongoose = require(" ...

Unable to establish a websocket connection with either Amber or NPM, uncertain of the reason

Amber CLI (amberframework.org) - v0.11.3 Crystal 0.27.0 [c9d1eef8f] (2018-11-01) LLVM: 4.0.0 Default target: x86_64-unknown-linux-gnu npm 3.5.2 Attempting to incorporate sockets using Crystal Lang and Amber has hit a snag. Despite following the guidelines ...

How can you dynamically change the value of a React datetime slider picker using code?

I can't figure out how to programmatically update the value of the React datetime slider picker, especially when I click on a button. The rendering code for the widget looks like this: <RDSPwidget enableSecond={true} /> This is how my ...

Exploring the power of Ionic and AngularJS in making secure HTTPS Post Requests

I've been attempting to make a request to an HTTPS server via the post method within my Ionic app, but I keep running into issues. I've tried two approaches so far - one using $http, and the other using $.ajax. Unfortunately, neither method has y ...

Error: Attempted to call $scope.map.control.getGMap function when clicking on the Map, but it is not defined

I'm currently working with Angular-Google-MAP and I'm trying to add a marker to the map. However, whenever I click on the map, I receive an error message saying $scope.map.control.getGMap is not a function. This error is occurring within the geoc ...

Enhancing data binding in Angular 2.0 with string interpolation

In my script, I am working with a string that goes like this: {name} is my name. Greeting {sender} Is there a module available in Angular 2.0 that allows me to use something similar to the string.format() function in C#? I understand that it can be achie ...

Obtain the result of the Mongoose find operation

Greetings, I am facing a challenge with accessing elements returned from a find operation in Mongoose due to the asynchronous nature and callback functions. Below is the code for reference: function retrieveBudgets(email, callback) { models.User.f ...

Creating a JSON array with a single item in Rails using Jbuilder

I am currently in the process of grasping how to utilize Jbuilder methods directly within a class. My objective is to convert an object into an array with a length of one in order to comply with the expected JSON specifications. Below is an illustration o ...

Submitting an AJAX request to upload an XML file and an image file simultaneously in one call

I need to send both an uploaded image and an uploaded XML file to a PHP file using a single AJAX call. I have tried using two form data instances, but I am not sure if this is the correct approach. <input type="file" class="form-control-file" name="fil ...

The functionality of the jQuery function is disrupted when I navigate to a different page/row or perform a search for specific items

Recently, I created a JQuery function that deletes the selected row. Although I am aware of the DataTables option available for this purpose, I chose to implement it myself using just JQuery and JSON without relying on AJAX. However, a problem arises when ...

A guide on wrapping a resource that relies on an asynchronous call

I am facing a challenge with a service that wraps a resource. I recently updated it to include a parameter (websiteId) fetched from an asynchronous call. Initially, I attempted to simply nest the resource within another resource, but encountered a typical ...

Tips for customizing the checked color of Material UI Radio buttons

If I want my radio button to be green instead of the default options (default, primary, secondary), how can I achieve that? I attempted to override the color using the classes prop like this: const styles = theme => ({ radio: { colorPrimary: { ...

Discover the step-by-step process of combining an array with JSON to create the desired outcome

I am working with a JSON array that looks like this: var row={ shopId: 3, shopName: '1', address: 'abc', contactNumber: 1234 } Alongside, I have another array: var data= [ { imageId: 1, shopId: 3, imageUrl: 'aaa' }, ...

Converting a Curl command to a JavaScript POST request: best practices

Is it possible to convert the given curl code into a JavaScript post request that will function effectively in all browsers? curl https://connect.stripe.com/oauth/token \ -d client_secret=sk_test_f7PKXx5NRBFG5r41nTrPT7qB \ -d code="{AUTHORIZATIO ...

Does jQuery mobile lack a back button feature?

Thoughts swirling in my mind: <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title></title> <script src="<?php echo base_url();?>/assets/js/vendor/modern ...

How can I attach an event listener to each row in a table that is dynamically generated?

I am currently working on a table that is being populated using data from a JSON file. The number of entries in the JSON file can vary, resulting in different lengths for the table rows. Each row includes a bootstrap dropdown button with links for actions ...