What is the process for updating the list to retrieve fresh data from the service?

I am currently in the process of calling a web service to retrieve data and display it in a list using directives.

  • Upon loading my fiddle, I successfully load data from a JSON file. The data is displayed correctly in the list.
  • If I click the delete button, all items are removed from the list, which works as expected.
  • However, when I click the refresh button, I want to call the service again to fetch fresh data but it does not show up in the list. Why?

Here is my code snippet: https://jsfiddle.net/8fjhLqnw/10/

.controller('he', function($http, $scope, sharedData) {
    var h = this;

    h.referesh=function(){
        sharedData.get();
    }
    h.delete = function() {
        sharedData.delete()
    }
});

Please check out the updated version on Plunker:

http://plnkr.co/edit/iMpStNneDmIsabTnFqpP?p=preview

In simple terms, clicking the refresh button should load data from data.json and display it in list form.

Answer №1

Check out the latest code snippet

The issue arises from constantly refreshing the reference to sharedData.data in your refresh function. The f controller establishes a binding to sharedData.data (i.e. vm.data = sharedData.data) before the data is actually refreshed, causing the vm.data reference to remain static (pointing to the original deleted array). To resolve this, create a direct reference to sharedData itself and access the data property internally from the template:

// continuation of module definition
.directive('tm', function() {

    // utilize vm.sharedData.data in the template
    return {
        restrict: 'E',
        template: '<div><ul><li ng-repeat="n in vm.sharedData.data">{{n.name}}</li></ul></div>',
        scope: {},
        controller: 'f',
        controllerAs: 'vm'

    };
}).controller('f', function($http, $scope, sharedData) {
    var vm = this;
    // initialize shared data
    sharedData.get().then(function(){
    vm.sharedData = sharedData;
    });

Following a data refresh, the data property within sharedData will reset and be reflected in the template because the scope maintains a constant reference to sharedData (which remains unchanged). Consequently, any modifications made to the sharedData object (such as refreshing the data property) will be detected by the template.

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

Exploring the Realm of Angular Controllers and Services: Embracing Triumphs and

Currently in the process of creating a service layer for an existing web app using Angular. I am transitioning $http requests and data manipulation to custom Angular services. While I have a good understanding of Dependency Injection in services, I am enco ...

Unable to display bar chart on PHP webpage showing database number volumes using JavaScript

I'm currently working on generating a bar chart to show the number of bookings per month. I have two separate SQL queries that retrieve the data correctly, as confirmed by testing. However, when I try to run the file in my browser, nothing is displaye ...

JavaScript/CSS memory matching game

Just starting out in the world of programming and attempting to create a memory game. I've designed 5 unique flags using CSS that I want to use in my game, but I'm feeling a bit stuck with where to go next. I understand that I need some function ...

What could be causing the inconsistency in the success rate of my Get request, with it working occasionally but returning a

Why is it that my Get request works on occasion, but most of the time it returns a 404 error? I've been experimenting by removing the "next()" function, but it doesn't make a difference. I've also tried placing "res.json(req.user.firstName) ...

directive in Angular pointing to a specific controller

I'm confused about where this error is coming from because I thought I had the syntax correct. An error of type TypeError: undefined is not a function was encountered. This particular error occurs in line 13 of the directive, where it says var refre ...

Dealing with Unhandled Promise Rejections in Express.js

I'm providing all the necessary details for this question, however I am confused as to why my callback function is returning an Unhandled Promise Rejection even though I deliberately want to catch the error: (node:3144) UnhandledPromiseRejectionWarni ...

What is the best way to access attributes from a div element?

I am currently working on extracting attributes from within a div tag, specifically the custom attributes of the first child element. I am using web scraping techniques with Node.js and Puppeteer. My goal is to retrieve the custom attributes data-ticker, d ...

Unable to retrieve JSON data in servlet

I am having trouble passing variables through JSON from JSP to a servlet using an ajax call. Despite my efforts, I am receiving null values on the servlet side. Can someone please assist me in identifying where I may have gone wrong or what I might have ov ...

"Troubleshooting null values in an Angular form submission handled by a C# MVC

Having issues sending data from AngularJS to a C# MVC controller. Even though the data is collected properly (confirmed by viewing them with console.log), they are not being received correctly in the C# controller, resulting in null values being stored in ...

Properly maintaining child processes created with child_process.spawn() in node.js

Check out this example code: #!/usr/bin/env node "use strict"; var child_process = require('child_process'); var x = child_process.spawn('sleep', [100],); throw new Error("failure"); This code spawns a child process and immediately ...

Displaying or concealing dropdown menus based on a selected option

My goal is to have a drop-down menu in which selecting an option triggers the display of another drop-down menu. For example, if I have options like "Vancouver," "Singapore," and "New York," selecting Vancouver will reveal a second set of options, while ch ...

Is it possible to create a dynamic zig-zag design with CSS that

I am looking to design a dynamic snake/zigzag layout that consists of square images and circles, starting from the center of the container and descending in a winding fashion. The number of elements is not fixed and is generated based on data received fro ...

Exploring the capabilities of Jasmine testing with AngularJS's $locationChangeSuccess event

I'm trying to figure out the best way to test this code snippet. How would you suggest writing a test for it? $scope.$on('$locationChangeSuccess', function () { $(".modal-backdrop").removeClass('modal-backdrop' ...

Merging the functions 'plainToClass' and 'validate' into a single generic function in NodeJs

Here's the issue I'm facing: export const RegisterUser = async (request: Request): Promise<[number, UserResponse | { message: any }]> => { let userRequest = plainToClass(UserRequest, request.body); let errors = await validate(u ...

How to access data from a child component in a Vue 3 template

Within my project, there are three Vue components that utilize the Composite API with the setup option. My goal is to access data within a nested tree structure. The code below provides a simplified version of what I am trying to achieve. The application ...

Performing unit testing on two services that reside in separate modules using the Jasmine testing framework

I have developed a service in Angular and you can view it on this PLUNKER. In the RouteService, I am injecting CommonService, $rootRouter, ModalService. Please note the following module structure : CommonService belongs to mysampleapp.core RouteS ...

The functionality of Object.assign in REACT is producing unexpected and incorrect results

Hey everyone, I have a project in React with 3 components. My goal is to extract the state from these 3 components and combine them into one JSON object on a final page. The components are not nested as child and parent, so my workaround was to set the st ...

Error in compiled.php on line 7772: Laravel throwing a RuntimeException when sending HTTP requests from Angular

Hey there, I've been encountering an error intermittently while using Angular $http methods with a Laravel API. Can someone please explain what this error means and suggest potential solutions? I've shared the error log on CodePen for easier refe ...

Attempting to grasp the sequence in which setTimeout is ordered alongside Promise awaits

I've been puzzling over the sequence of events in this code. Initially, I thought that after a click event triggered and Promise 2 was awaited, the for loop would resume execution once Promise 1 had been resolved - however, it turns out the outcome is ...

issues with the redirection functionality in the Play framework

I am currently working on an application that extracts data from Twitter profiles. I want to give the user the ability to select which parts of their profile should be used (for example, excluding tweets). To accomplish this, I plan to incorporate checkb ...