Tips for refreshing a list in Angular using a service after form submission

As a beginner with Angular, I am setting up a simple "submit comment" and "display list of comments" page. My goal is to automatically update the list of comments after submitting a new one, without having to manually refresh the page.

Here are my controllers:

app.controller('FormController', function($scope, CommentService) {
    $scope.comment = {}; //this will be filled out by a basic form
        $scope.submit = function() {
            return CommentService.post($scope.comment).then(function(){
                $scope.comment = ""; //clears form after submission
            });
        }
});

app.controller('CommentsController' function($scope, CommentService) {
    CommentService.list().then(function(comments){
        $scope.comments = comments.data;
    });
});

And here's my service:

app.service('CommentService', function($http) {
    this.post = function(comment) {
        return $http.post('/api/v1/comments/', comment);
    };

    this.list = function() {
        return $http.get('/api/v1/comments/').
                success(function(data) {
                    return data;
                });
    };

    //How can I link these two controllers?
});

The HTML form and list are very generic, using "ng-repeat" to display comments. Am I heading in the right direction? Is there a simple way to have the list of comments updated when a new one is submitted via the form?

Thank you for your help!

Answer №1

To achieve the desired outcome, you can make the following modifications to align with your program's semantics.

In the controller:

var getList = function() {
    $scope.comments = CommentService.list();
};

CommentService.registerObserverCallback(getList);

Within the service:

var observerCallbacks = [];

// Register the observer's callback in the callback list.
this.registerObserverCallback = function(callback){
  observerCallbacks.push(callback);
};

// Function to notify observers and call the registered callback
var notifyObservers = function(){
  angular.forEach(observerCallbacks, function(callback){
   callback();
 });
};

this.post = function(comment) {

    return $http.post('/api/v1/comments/', comment).success(function(data, status, headers, config) {
        notifyObservers();
    })
 };

Essentially, your controller informs the service that it is observing its actions and requests a callback function to be executed when any action occurs. This callback is passed as getList. The service then registers the observer and executes the callback after the successful completion of post().

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 most efficient way to retrieve the current user's ID within Loopback?

Given the instability and deprecation of loopback.getCurrentContext(), what strategies can I use to accurately identify users when they interact with API endpoints? Is it feasible to include the token ID in the request payload for verification purposes? H ...

Error: Vue.js application requires the "original" argument to be a Function type

I am facing an issue when trying to call a soap webservice using the 'soap' module in my Vue SPA. Strangely, I encounter an error just by importing the module. Despite my extensive search efforts, I have not been able to find a solution yet. Her ...

How can a method inside an object property of the same class be invoked in JavaScript?

I'm faced with a bit of confusion here. I have a class property called hotspot of type object, declared as follows: Cannon.prototype.hotspot = {stuff: this.blah(...) }; The method blah() is actually a prototype of the same 'class': Canno ...

Obtain the HTTP response status code within a middleware function

I am currently developing an application where I want to create a custom logging system for every request made. For each request, I want to log the timestamp, method, route, and the response code sent to the client. Here is the code I have at the moment: ...

Retrieve information from a website and transfer it to a Google spreadsheet

Despite the wealth of information on this topic, I have yet to find a solution that works for me. My goal is to transfer variables obtained from another website to Google Spreadsheet. These are the variables: var a = parseInt($('table.thinline:eq(4) ...

Obtain the date in the following format: 2016-01-01T00:00:00.000-00:00

Can someone help me convert this date to the correct format for the mercadolibre api? I need it to be like this: 2016-01-01T00:00:00.000-00:00 However, when I try with the following code: var date_from = new Date(); date_from.setDate(date_from.getDa ...

Sending an integer through an AJAX request without relying on jQuery:

I am having trouble sending an integer named 'petadid' from my JavaScript to the Django view called 'petadlikeview'. The data doesn't seem to be reaching the view, as when I print 'petadid' in the view it displays as &apo ...

Sending mass text messages with a customized message for each phone number - A guide using Twilio

I have a batch of 100 to 1500 phone numbers that I need to send SMS messages to. Each message should include the recipient's name associated with the phone number in the text. How can I achieve this using Twilio? client.notify.services(notifyServiceS ...

The anticipated conclusion of the MIME multipart stream has not been reached. The MIME multipart message remains incomplete

I am currently working on an Angular application that is written in Typescript and has a backend built with ASP.Net Web Api. In my project, I am trying to implement the ng-file-upload directive for uploading image files. However, when I attempt to upload a ...

The existence of useRef.current is conditional upon its scope, and it may be null in certain

I'm currently working on drawing an image on a canvas using React and Fabric.js. Check out the demo here. In the provided demo, when you click the "Draw image" button, you may notice that the image is not immediately drawn on the canvas as expected. ...

Angularjs input type=number directive is malfunctioning

I have an input field with the type "number" that allows both whole and decimal numbers. However, I only want to allow whole numbers to be entered into the input. I have created a directive that works for input fields with type "text", but it does not work ...

Is it possible to update both package-lock.json and package.lock simultaneously?

Before releasing to NPM, I always make sure to update the minor version. My usual process includes: - Modifying the package.json - Executing npm i to synchronize package-lock.json with the changes. This prepares both files for publishing. Is there a simpl ...

Creating a customizable CSS selector in an Angular.js application

I'm currently developing a project in Angular.js involving a plane view where various objects are located. Every time a user drags an item from the left menu bar to the center of the screen, a new object is created. The unique CSS class for each item ...

Progress Indicator on my online platform

I've been attempting to remove a loading bar from my website, but I can't seem to locate it in the site files. I even tried using Google Chrome's inspection tool, but I couldn't pinpoint the loader. Can someone please assist me? Visit ...

Implementing a universal font-size adjustment feature according to user preferences

Is it possible to allow users to choose the font size for the entire application, offering three options: Big, Medium, Small? If a user selects "Big", all fonts in the application will be resized globally. I have spent time researching this issue but ha ...

Angular is able to select an element from a specified array

I'm currently struggling with using Angular to manipulate a TMDB API. I am having difficulty retrieving an item from an array. Can someone provide assistance? Here is the response that the array returns: { "id": 423108, "results ...

Converting multiple tiff image files into a single image in Angular 9: A step-by-step guide

I am currently developing a web application using Angular 9. I am looking to incorporate a feature that will enable the conversion of multiple Tiff images into a single PDF or window.URL.createObjectURL(blob) of pdf. let images = ["http://netghost.nar ...

Creating a Draft.js selection with a specified start and end point

Looking for a way to replace the last insertion in Draft.js For instance, Original string -> aaazzz After inserting 'bbb' in the middle -> aaabbbzzz Replace last insert with 'ccc' -> aaaccczzz Replace last insert with &apos ...

Leveraging datatables for efficient table searching in Asp.net MVC

When using datatables to search a table, I encountered an issue where adding another table row caused some problems as datatables requires the same number of rows and columns. Is there a workaround for this? I really want to utilize datatables but also nee ...

Increase the object name in localStorage to save information entered in input fields

For testing purposes only - do not use for production. I am experimenting with storing data from 3 different input fields (text and numbers) in localStorage. My goal is to have the values increment every time the form is submitted. However, I am encounte ...