The functionality in AngularJS when inputting data into a form does not trigger a complete page refresh

I am facing an issue with my page where I display a list of titles (referred to as suggestions in my app) directly fetched from a database using a service. Additionally, there is a form for users to input new titles. The problem arises when a new title is entered into the form - although the data gets inserted into the database, the page does not refresh properly. The title ends up being inserted twice in the database and also displayed twice on the view page. Even if I manually delete the first title from the database and insert a second one, the first title still appears on the page.

Below is an excerpt from my controller:

app.controller('HomeController', [
    '$scope',
    '$http',
    'get_suggestions',
    function($scope, $http, get_suggestions) {

        $scope.addSuggestion = function() {

            var title = $scope.newsuggest.title;

            if (!title || title === "") {
                $scope.error = "Enter a suggestion";
                return;
            } else {

                $http.post('add_suggestions.php', {
                        title: $scope.newsuggest.title
                    }).success(function(data, status, headers, config) {

                        $scope.posts.push({
                            title: title,
                            upvotes: 0,
                            comments: []
                        });

                        $scope.newsuggest.title = '';
                        $scope.error = '';
                        $scope.$apply();
                        $route.reload();

                    })
                    .error(function(data, status) {
                        $scope.errors.push(status);
                    });

            }
        }


        get_suggestions.success(function(data) {
            $scope.posts = data;
        });

    }
]);

Here is a snippet of my view page:

    <div class="container">
    <div ng-repeat="post in posts | orderBy:'upvotes'" class="col-md-6" style="clear:both; padding-bottom:20px;">

        <p class="title">{{post.title}} </p>
        <p>Votes: {{post.upvotes}} </p>

    </div>
</div>

<div class="container">
    <div class="col-md-6" style="clear:both; padding-bottom:20px;">

        <form ng-submit="addSuggestion()" style="margin-top: 50px">
            <h3> Send a suggestion </h3>
            <div class="form-group">
                <input type="text" class="form-control" name="title" ng-model="newsuggest.title"></input>
                <div>{{error}}</div>
            </div>
            <button type="submit" ng-click="addSuggestion();" class="btn btn-primary">Send</button>
        </form>

    </div>
</div>

Answer №1

By utilizing $route.reload(); in your code, you already have the functionality to reload. The issue lies in the fact that you forgot to inject $route into your controller, resulting in an error being displayed in the browser console.

TypeError: Cannot read property 'reload' of undefined

Furthermore, there is no need to utilize $scope.$apply(); when performing a reload.

app.controller('HomeController', [
    '$scope',
    '$http',
    'get_suggestions',
    '$route', //Be sure to inject the route service 
    function($scope,
        $http,
        get_suggestions,
        $route) {
    }
]);

OR

You can alternatively use $window.location.reload();. Just remember to inject $window into your controller.

Answer №2

  1. Insert $Route.

  2. Take a look here

    $scope.posts.push({
                            title: title,
                            upvotes: 0,
                            comments: []
                     });
    

Q What does it do?

A you have a $scope named posts linked to your UI. Thus, any data added will be visible to the end user without needing a refresh.

I have two suggestions for you.

  1. Delete that code as mentioned above. Then use $route.reload(); to trigger a page refresh. After the page is refreshed, ensure your API returns a JSON of titles and bind it to the $scope.posts variable (which may be used in Angular's init method).

  2. My suggestion is if you have an init method like this.

      $scope.pageInit=function(){
      // your API call to fetch data.
      // after receiving a JSON list of titles, make sure to bind it with the $scope.posts variable.
       $scope.posts=titlesObj;
    }
    

Rather than using $route.reload(), you should invoke the $scope.pageInit function to get the latest data.

       $scope.newsuggest.title = '';
       $scope.error = '';
       $scope.$apply();
       // $route.reload();
       $scope.pageInit(); // this will retrieve all the updated information.

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

How to retrieve a Facebook user access token using server-side scripting with Node.js

I am looking to retrieve my Facebook ad campaign statistics every 30 minutes using Nodejs. To accomplish this, I require a user access token that needs to be refreshed for every request due to expiration. Any suggestions on how I can achieve this solely ...

Discover the process of utilizing doc.getElementbyClassName to determine if any of its elements are blank

On my HTML invoice table, I sometimes have empty elements that cause the row to misalign. To fix this, I want to add whitespace if an element is empty. Here is the structure of the table: <div class="invoiceTable"> <div class="titles2" style=" ...

Ensuring JS consistently monitors changes in value

Is there an equivalent of (void update) in Unity that is called every frame in Web Development (using JavaScript)? "I want it to continuously check if certain values have changed and then update them accordingly." let governmentprice = parseFloat(select ...

Tips for retrieving specific data from a variable in an object using PHP

I am facing a challenge in accessing the value of an object with an array in PHP Laravel. Currently, I have successfully accessed the information using the following method. However, the issue arises when the position of the required information changes, f ...

Duplicating an array retrieved through a jQuery ajax request

Currently, I am encountering an issue while attempting to duplicate a JSON array within this specific JavaScript function: var test = new array(); function showUser(user, pass, remember) { $.getJSON("login.php", { username : user, password : pass, che ...

Initiating Axios requests after a period of time, such as a day, week, or

In my React project, I have implemented functions that make Axios calls to update a user's membership type in the database to daily, weekly, or monthly. The issue is that these changes must be manually reverted back to "Expired". Is there a way to cre ...

How to accurately incorporate the "HH:MM" time format into a Date Object in JavaScript

I need to convert a specific time of the day into a Date Object. The time is in String format and is in CET (Central European Time). In CET, "16:00" translates to "15:00" in UTC during Winter time. The code snippet below achieves this conversion in node.js ...

The jQuery closest selector seems to be malfunctioning when trying to scroll and focus on a specific class

My HTML code snippet is as follows: <div class="main"> <div class="sub-1"> <select> <option>1</option> <option>2</option> </select> </div> <div class="sub-2"> ...

Exploring the Possibilities of Wordpress Search with Multiple Dropdown Options

Is it possible to search across multiple categories? For example, I have 4 dropdown menus: 1. City 2. Area 3. Month 4. Products/Services When a user visits my site, they will see a static page with 4 dropdown lists and a "search" button. After the user ...

WebApp specifically designed for iPads that mimics the functionality of a swipe

I am in the process of developing a full-screen web application for an iPad that will showcase a series of images in a slider format. The users should be able to swipe between the images and click on one to view it in detail. Below is an example showcasin ...

How to Pause or Temporarily Halt in Jquery?

Looking to lift the object up, wait 1000ms, and then hide it. I found this snippet of code: $("#test").animate({"top":"-=80px"},1500) .animate({"top":"-=0px"},1000) .animate({"opacity":"0"},500); However, using ".animate({"to ...

Is JSONP functioning properly in Chrome but not in Firefox or Internet Explorer?

I'm currently in the process of developing a mobile site and I've opted to use JSONP requests via jQuery to communicate with the data server in order to retrieve information for display on the mobile site. The advice given to me was to avoid usin ...

Change the page using JavaScript after submission

I am currently working on incorporating Firebase authentication into a Node.js Express-based application. However, I have encountered the following error: nexttick.js:45 Uncaught TypeError: Cannot read property 'redirect' of undefined This ...

Determining the length of a specific array field in PHP

Looking to determine the length of a specific field within a Multidimensional Array? Unsure how to proceed and only finding references to sizeof(array) or count(array,count_recursive)? In JavaScript, this can be achieved as follows: var modalInfo = { ...

Transform a REACT js Component into an HTML document

I'm working with a static React component that displays information from a database. My goal is to implement a function that enables users to download the React component as an HTML file when they click on a button. In essence, I want to give users ...

What is the proper way to invoke a different method from a static method in ReactJS?

Recently, I updated some outdated events and implemented the 'getDerivedStateFromProps' static method. I'm wondering if it's possible to invoke an instance method from within this static method. ...

Eliminate any properties with values that exceed the specified number in size

:) I'm trying to create a function that removes properties with values greater than a specified number. I've searched through multiple resources like this question on how to remove properties from a JavaScript object and this one on removing pro ...

Utilizing ReactJs to Generate a Random Number for Visualization in a Material UI Progress Bar

I am looking to generate a random number for my test functionality in order to display it within a Material UI Progress bar. I have successfully implemented this piece of JavaScript code on JSFiddle, but now I want to integrate it into my React application ...

Unable to retrieve data from object properties despite their visibility

I am encountering issues accessing object properties, as they keep returning as undefined. I have attempted console.log(JSON.parse(this.$store.state.user.userId)); as well as console.log(JSON.parse(this.$store.state.user[0].userId)); However, when I ...

JavaScript Mortgage Calculator: Issue with Input Field Formatting when Adding Commas

I am currently developing a mortgage calculator and I would like to include commas in the form fields. The code I found worked well initially, but once numbers reached over 1,000,000, the formatting became strange. Since I am new to JavaScript, any guidanc ...