Trouble with saving $http get response data to a scope variable

Here is the code snippet that is facing an issue in assigning return values to the scope variable.

app.factory("appService",function($http){
  var promise;
  var lists = {
    async: function() {
      var promise = $http.get("http://localhost:81/hrms/public/languagesService").then(function (response) {
        return response.data;
      });
      return promise;
    }
  };
  return lists;
});

The $http get request returns a successful response with status code 200. Below is how the service is utilized in the controller:

app.controller("AppCtrl",function(appService,$scope,$http,$filter) {
  $scope.language = "";

  var sortingOrder = 'id';
  $scope.sortingOrder = sortingOrder;
  $scope.reverse = false;
  $scope.filteredItems = [];
  $scope.groupedItems = [];
  $scope.itemsPerPage = 4;
  $scope.pagedItems = [];
  $scope.currentPage = 0;
  $scope.items = [];


  $scope.itemlist = function() {

    appService.async().then(function(d){
      $scope.data = d;
    });

  }

  $scope.items = $scope.itemlist();

However, the $scope.items variable remains empty. I need help on how to populate $scope.items with the response data from $http.get(). Attempting to use $scope.items.push(d) did not yield any results...

My goal is for $scope.items to store the data retrieved from $http.get().

Answer №1

It seems like the answer lies within an array structure. Therefore, you have the option to initially return an empty array and populate it with data once the response is received:

$scope.itemList = function() {
   var result = [];
   appService.loadData().then(function(data){
      $scope.data = data;
      result.push.apply(result, data);
   });
   return result;
};

$scope.itemsArray = $scope.itemList();

In this code snippet, we utilize the apply method to efficiently add multiple elements at once using the push function.

Answer №2

Hey there, have you considered assigning variable d to $scope.items like this?

app.controller("AppCtrl", function(appService, $scope, $http, $filter) {
  $scope.language = "";

  var sortingOrder = 'name';
  $scope.sortingOrder = sortingOrder;
  $scope.reverse = true;
  $scope.filteredItems = [];
  $scope.groupedItems = [];
  $scope.itemsPerPage = 5;
  $scope.pagedItems = [];
  $scope.currentPage = 1;
  $scope.items = [];

  appService.loadData().then(function(d){
      $scope.items = d;
    });
})

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

Vue component failing to display data passed as props

As a Vue beginner, I ventured into creating a custom component and attempted to bind everything just like in the basic Vue CLI template. Here is my code snippet. Circle.vue <template> <div :style="custom"> </div> </template&g ...

How the React Component Class Executes OnChange Event in a Closure

When working on my React code, I found myself creating a closure by calling "onChange." class CityInput extends React.Component { constructor( props ){ super( props ); this.state = { city : "", country : "" ...

Developing a unique JavaScript object by extracting information from a jQuery AJAX response

Is there a recommended approach for creating a custom JavaScript object that contains data retrieved from a jQuery AJAX request? I'm considering two methods, but unsure which is the most appropriate. The first method involves including the AJAX reques ...

jQuery script located on local server fails to function

After downloading the jQuery.js file from jQuery.com, I made sure to save it in multiple locations - including JRE/Lib and my desktop where the HTML file that calls it is located. The script reference looks like this: <head> <script type= ...

The database is not being updated with the new values

Is it possible to retrieve data from a database and modify it using AJAX? I tried changing the input, but AJAX keeps sending the original data stored in the database. <script> function showMore(str) { var xhttp; if (str.length == ...

Determine the number of centimeters on the page as you scroll with jQuery

While searching for plugins that count up and down, I came across many. However, I am looking for something more unique: Imagine having an HTML page that is 70,000cm high. Now picture a counter in one corner that displays the height you are currently at a ...

Experiencing difficulties with mocha and expect while using Node.js for error handling

I'm in the process of developing a straightforward login module for Node. I've decided to take a Test-Driven Development (TDD) approach, but since I'm new to it, any suggestions or recommended resources would be greatly appreciated. My issu ...

Creating a list of font sizes for each <p> tag in my HTML document

I am looking to create an array containing the font sizes of all the p tags in my HTML document. How can I specifically target only the p elements and not their parent elements? ...

Is it advisable to avoid accessing the factory function using a provider.$get during the configuration phase?

This is a genuine inquiry, and I am seeking honest and justified explanations on why I ought to avoid doing this... angular .module('X', ['Y']) .config(function (myFactoryProvider, myServiceProvider) { myFactoryProvider ...

Having trouble with getting Express to automatically redirect to the main page upon user login

Currently, I am working on setting up a user login section. Despite the user_router successfully sending a JSON response, I am facing an issue with getting Express to send a new HTML page back to the client. The initial page offered is login.html, which co ...

Searching through multiple columns in datatables

I encountered an issue with searching multiple columns in my serverside datatables. Individual column searches work fine, but when trying to search on more than one column simultaneously, the filter does not function as expected. For example, searching by ...

sending parameters into a regex within a function

Struggling to pass a variable into a robust regex, managing to make it work outside the function but unable to figure out how to get it working within a function. Not sure why match[1] is returning null or how to find words after a keyword. Here's wh ...

Error: Attempting to assign a value to a property of #<Object> that is read-only

I'm working on a task management application and encountering an issue when trying to assign an array of tasks stored in localStorage to an array named todayTasks. The error message being thrown is causing some disruption. https://i.sstatic.net/uFKWR. ...

Managing Subdomains in Nuxt.js Using Vue.js

I am currently developing a Nuxt.js (vue.js) application. I am aware that Nuxt automatically generates routes based on the directory structure within the 'pages' folder. I am curious about how it would handle subdomains. My goal is to establish ...

Mastering the art of utilizing generic types efficiently within Higher Order Component structures

My parent component (Grid) passes props to a higher-order component (hoc), let me show you: <QuickBooksTable itemList={quickBooksList} /> Here is the QuickBooksTable component: export const QuickBooksTable = withIntegrationTable(props: : WithIntegra ...

Transferring information from an online platform onto pre-arranged sheets for hard copy

Has anyone had success printing from a website? I have some papers that are already printed with checkboxes. These checkboxes need to be filled in based on information entered through a web form or retrieved from a MySQL database. All of this information ...

Adjustable height and maximum height with overflow functionality

Currently, I am in the process of developing a task manager for my application and facing an obstacle when trying to calculate the height of a widget. My goal is to determine the maximum height (assuming a minimum height is already set) by subtracting a ce ...

Is there a way to apply toggling and styles to only the card that was clicked in Vue.js?

DisplayBooks.vue consists of a single page responsible for showcasing books fetched from a backend API. Each card on the UI features two buttons - ADD TO BAG and ADDED TO BAG. When a user clicks on the ADD TO BAG button of a specific card, it should toggle ...

TypeError: Unable to execute products.map as a function

I'm encountering an issue where product.map is not functioning as expected, despite trying multiple fixes found online. Additionally, when I console.log(response.data), it shows a successful response. Using React version 7.0 constructor () { ...

After triggering an action, I am eager to make a selection from the store

To accomplish my task, I must first select from the store and verify if there is no data available. If no data is found, I need to dispatch an action and then re-select from the store once again. Here is the code snippet that I am currently using: t ...