Issue with model not being updated after making a request using $http service

I have a hunch as to why it's not functioning properly, but I'm unsure on how to troubleshoot this. Despite looking at similar questions and answers on SO, I am unable to resolve my issue.

My goal is to trigger a service upon page load in order to display a table of data - for simplicity let's refer to this as a list of URLs.

The model should consist of { urls }, returning an array of URLs that would be utilized in ng-repeat in the future.

Here is my controller:

function UrlListCtrl($scope, UrlService){
  $scope.urls = UrlService.getUrls();
}

And here is the service:

function UrlService($http) {
  return {
    getUrls: getUrls
  }
  function getUrls() {
    console.log('Fetching Urls...');
    return $http.get('urls/get')
      .then(function(response) {
        console.log('response:', response.data);
        this.urlsResults = response.data;
    });
  }
}

The service does execute, however it fails to update the view. How can I address this issue?

Answer №1

$http.get() is a method that performs an asynchronous operation and returns a promise. It is important to wait for this promise to be resolved before accessing the data from the response.

In the provided code snippet

$scope.urls = UrlService.getUrls();
was assigning the promise itself, rather than its results, to $scope.urls. As a result, the view did not update when the operation completed.

Controller:

function UrlListCtrl($scope, UrlService){
  UrlService.getUrls().then(function(response) {
     $scope.urls = response.data;
  });
}

Service:

function UrlService($http) {
  return {
    getUrls: getUrls
  }
  function getUrls() {
    console.log('Fetching Urls...');
    return $http.get('urls/get');
  }
}

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

Asynchronous waterfall call in Node.js to call the method before

Is it possible to invoke a previous method within async.waterfall from a subsequent method? async.waterfall([ function (callback) { }, function (reservationStatus, callback) { }, function (reservationStatusList, f ...

Starting a line series from the beginning of the y-axis on a bar chart using chart.js

We have a new request from the business regarding the implementation of chart.js. Take a look at the image below, which shows a combination of bar and line charts. The line chart contains only a few data points. Within the application, users can choose a ...

"Integrating `react-textarea-code-editor` with Remix: A Step-by-Step Guide

Upon loading the root of my web app, I encountered an error. The react-textarea-code-editor component is accessed via a separate route. The same error persisted even after following the suggestions provided here: Adding react-textarea-code-editor to the ...

Styling and Script Files on a JQuery Mobile Website

Is it necessary to include CSS and JS files in every HTML page for a mobile site developed with JQueryMobile? <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" /> <script src="http://code.jquery.com/jqu ...

Can the issue of mangling be avoided during .NET minification?

Currently, I am utilizing the .NET Bundling and Minification feature to bundle and minify the files for my application. While this method works well, I am interested in exploring alternative solutions due to its complexity. Specifically, I am attempting t ...

Disable the meta tags in Zurb Foundation 5

I have searched extensively online but haven't been able to find a solution for this issue. How can I disable these zurb foundation 5 meta tags in the <head>: <meta class="foundation-mq-small"> <meta class="foundation-mq-small-only"> ...

Any advice on resolving sorting issues in an angularjs select box and ensuring the correct item is selected?

I need help creating an angularjs select box with a list of months. Currently, I am passing the list of month names from the server using C#. Initially, I attempted to pass the months as a dictionary: var months = new Dictionary<int, string> { { ...

Securing Your ExpressJs API Files from Prying Eyes in Developer Tools

Typically, when I utilize developer tools in Google and choose to open an API file in a new tab, I am able to view the data as illustrated below. However, there are occasions where upon attempting the same action on certain websites, a security precaution ...

Can you combine multiple user validation rules with express-validator?

I have a set of rules that are almost similar, except for one where the parameter is optional and the other where it is mandatory. I need to consolidate them so that I can interchangeably use a single code for both cases. Is there a way to merge these rul ...

AngularJS ng-include nested form configuration

My application utilizes nested ng-includes. The outer include is a login screen for one application while the inner ng-include includes two templates. The login screen is designed in two steps where the email is checked first and then the password entered. ...

The div that scrolls gracefully within its boundaries

Currently, I am working on a task that involves a div containing images that need to be scrolled left and right. I have successfully implemented the scrolling functionality using jQuery. However, I now face the challenge of ensuring that the content stays ...

Having trouble toggling journal entries in an HTML journal? The Jquery function might not be working properly

I have been tasked with creating a civil war journal for my 8th grade Social Studies class and I decided to present it as an HTML file featuring the title and date of each journal entry. The goal is to allow users to click on each entry to open it while au ...

troubles with compatibility between bootstrap.css and IE11

I am currently developing a web application using AngularJS and bootstrap.css. While everything appears fine on Chrome, I am facing some formatting issues on both Firefox and IE11. HEAD <head> <meta charset="utf-8"> <meta http-equi ...

Encountering an error when importing chart.js-plugins-annotations

import { annotation, Chart, defaults } from 'chart.js'; An issue arises when using this import statement: localhost/:1 Uncaught TypeError: Failed to resolve module specifier "chart.js". Relative references must start with either &quo ...

Changing the content of the initial post in a loop on WordPress

<?php $freeadvice=new WP_Query('category_name=freeadvice&showposts=10'); while($freeadvice->have_posts() ): $freeadvice->the_post(); ?> <li class="event"> <input type="radio" name="tl-group" /> ...

Guide to shutting down a print dialogue in a web browser with javascript

Looking for a way to close the print window of a browser using JavaScript or any other method, with JavaScript being the preferred option. Any help on closing the print window for IE, Chrome and Safari would be greatly appreciated. Please assist.. Thank ...

How can non-numeric characters be eliminated while allowing points, commas, and the dollar sign?

Looking for an efficient method to filter out all characters except numbers, '$', '.', and ','. Any suggestions on achieving this task? ...

Nuxt.js static pages with relative URLs

I am currently working on developing static pages with Nuxt.js (MPA). After executing the generate command, I noticed that all the URLs in the <nuxt-link> tag start from the root directory, specifically /. For instance, my project structure looks lik ...

Is it possible to use HTML elements to trigger actions in order to display or conceal divs using JavaScript?

Beginner - I am currently working on a webpage using TinyMCE wysiwyg and I would like to implement a functionality where I can display or hide certain divs upon clicking a link/button. Unfortunately, due to the structure of the page, it seems that I ca ...

Start by setting up the Select box to include a loading option, which will then be removed once the

I am facing an issue with a select box in my form that loads data using a JSON request in AngularJS. To handle the delay in loading the data, I added a temporary option: <option value="">Loading...</option> However, once my model is loaded, t ...