Refreshing Information in Angular

I am attempting to create a reload data button. Here is the JSON structure I am working with:

    [
        {
            "name": "AAAAAA",
            "data": "False"

        },

        {
            "name": "BBBBBB",
            "data": "45%"
        },
        {
            "name": "CCCCC",
            "data": "12%"
        }
]

This is the JavaScript code I am using:

app.service('service', function($http, $q) {

  var deferred = $q.defer();

  $http.get('names.json').then(function(data) {
    deferred.resolve(data);
  });

  this.getNames = function() {
    return deferred.promise;
  }
});

app.controller('FirstCtrl', function($scope, service, $http) {
  var vm = this;
  vm.reloadData = function() {
    console.log("reloading");
    vm.loadData();
  };

  vm.loadData = function() {
    var promise = service.getNames();
    promise.then(function(data) {
      $scope.names = data.data;
      console.log($scope.names);
    });
  }

  vm.loadData();
});

Here is my HTML code:

    <div ng-controller="FirstCtrl as vm">
      <table>
        <tbody>
          <tr ng-repeat="name in names">
            <td>{{name.name}}</td>
            <td>{{name.data}}</td>
          </tr>
        </tbody>
      </table>
      <button ng-click="vm.reloadData()">Reload</button>
    </div>

When I click the "Reload" button using the function "vm.reloadData()", nothing happens and my data does not refresh. Any help would be greatly appreciated.

Answer №1

Give this a try:

  1. I have removed the extra promise since $http itself returns a promise..
  2. Added a feature to not store request data in the cache.

       app.service('service', function($http, $q) {
          this.getNames = function() {
             return $http.get('names.json', { cache: false});
          }
        });
    
        app.controller('FirstCtrl', function($scope, service) {
          var vm = this;
          vm.reloadData = function() {
            console.log("reloading");
            vm.loadData();
          };
    
          vm.loadData = function() {
            var promise = service.getNames();
            promise.then(function(data) {
              $scope.names = data.data;
              console.log($scope.names);
            });
          }
    
          vm.loadData();
        });
    

Answer №2

According to your current implementation, you are storing the resolved promise in the service.

In order to correct this issue, it is advisable to declare deferred within the getNames() service method.

app.service('service', function ($http, $q) {
    this.getNames = function () {
        var deferred = $q.defer();
        $http.get('names.json').then(function (data) {
            deferred.resolve(data);
        });
        return deferred.promise;
    }
});

Answer №3

Revise the function code to look similar to this

this.fetchInfo = function() {
   return $http.get('information.json');
}

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 is the best way to delete the "Click to sort Ascending" text from the header of each column in a bootstrap-vue table?

Recently, I came across a bootstrap-vue table that caught my attention: https://i.sstatic.net/5jENs.png Below is the code snippet for the table setup: <template> <div class="container"> <h1 class="pt-2 pb-3">Bo ...

Angular ng-click function is not functioning properly within a DataTables table row

I am facing an issue in my application where I am using both Angular and jquery.dataTables. The problem arises when I try to incorporate the ng-click angular directive within the dynamically created table using datatables, as the ng-click event does not se ...

Add integer to an array of strings

Currently, I am utilizing an autocomplete feature and aiming to save the IDs of the selected users. My goal is to store these IDs in a string array, ensuring that all values are unique with no duplicates. I have attempted to push and convert the values u ...

What is the solution for displaying just a single panel?

Is there a way to ensure that only the hidden text is displayed when clicking on the button within each panel? Currently, both panels are being revealed simultaneously... import React, { useState } from "react"; import "./styles.css"; export default func ...

AngularJS and Spring Rest team up for seamless drag-and-drop file uploads

I have successfully implemented file upload using AngularJS and Spring REST, but now I want to change it to use dropzone.js or any other drag and drop file upload method. I tried using the dropzone.js library, but I am facing issues integrating it with Ang ...

AngularStrap - Streamline your application by loading only the essential modules

The documentation for AngularStrap mentions the plugin dependency for Datepickers requiring the tooltip module and dateParser helper module to be loaded. These docs currently use bootstrap-additions for styling purposes. Im currently utilizing angular ...

What is the best way to customize the appearance of a form element within an angular-schema-form schema without affecting the overall

Currently, I am in the process of constructing a form using the incredible angular-schema-form. Creating the form schema object has been a success so far. My goal is to configure all the form components within the schema using the x-schema-form property in ...

Whenever a new entry is made into the textfield, the onChange feature triggers a reset on the content within the textfield

I'm experiencing an issue while creating a SignUp authentication page with Firebase. Every time I try to input text in the text field, it gets reset automatically. I have been unable to identify the root cause of this problem. It seems to be related t ...

Add a new sibling item to Angular-UI-tree

I am trying to add a sibling item to a tree when clicked in angular-ui-tree (https://github.com/angular-ui-tree/angular-ui-tree) Here is an example of what I currently have: <item><input value"item A #1"><button>insert under</button& ...

Navigating with the keys is disabled until an item is chosen

Currently working on a Shopify website for a client and encountered an issue where the keys don't scroll down upon page load unless a specific element is clicked or tab is used. I am not sure what caused this unexpected behavior, it may have occurred ...

Is JavaScript overwriting the existing value?

I am completely new to JavaScript and I am struggling with a seemingly simple issue. I have an array of usernames that I am iterating over. My goal is to map these usernames to click event methods, although I am aware that this may not be the most efficien ...

There are no errors thrown when assigning a numeric value within an object literal

Here is a piece of code to consider: let logged = 1; let x = {logged} //{logged: 1} x['logged']; // 1 x['logged']['index']; //undefined x['logged']['index'] = 0; x; // {logged: 1} x['logged'] ...

Guide on navigating through various HTML pages with distinct parameters using Node.js (Express server)

Seeking assistance with a Node.js server that receives an ID as a query parameter. Each time a client connects with different parameters, I aim to serve them a unique HTML page containing a simple UI with 2 dynamic arrays. Everything seems to be working co ...

workflow for deploying Angular apps with Deployd and Grunt

Struggling to smoothly incorporate deployd into an existing Angular Grunt workflow. Has anyone successfully achieved this before? Here are the steps I've taken so far: Added deployd and grunt-deployd to the project Tweaked the gruntfile in vari ...

The eBay API is providing users with small thumbnail images with low resolution

Adding &outputSelector=GalleryInfo to the URL was supposed to give me a higher resolution thumbnail, but it doesn't seem to be working. I'm still new to JSON and the tutorial I'm following isn't very clear on the exact syntax needed ...

Python script utilizing Selenium to load only JavaScript content and excluding full HTML rendering

As I navigate through the link , I am on the lookout for the search bar marked with the class "search-field". The HTML snippet in question is as follows: from selenium import webdriver import time driver = webdriver.Firefox() driver.get("https://www.takea ...

Is OnPush Change Detection failing to detect state changes?

Curious about the issue with the OnPush change detection strategy not functioning properly in this demonstration. My understanding is that OnPush change detection should activate when a property reference changes. To ensure this, a new array must be set e ...

The reason for the undefined socket.id in the browser is due to a potential

When using console.log(socket), I am able to see a socket object in Firebug. Within this object, there is a property called id and I can view the value of this id. However, when I try to access it directly with console.log(socket.id), the result is undefin ...

Interactive image slideshow with custom tagging capabilities

Is there a ready-made open-source horizontal gallery slider package available that includes photo-tagging functionality using JavaScript and jQuery, suitable for use in personal portfolios? ...

Replace the function if it is specified in the object, otherwise use the default functionality

Having a calendar widget written in TypeScript, I am able to bind a listener to a separate function. However, I desire this separate function to have default functionality until someone overrides it in the config object passed to the constructor. Within th ...