remove information within callback

I came across this code snippet and encountered an issue while trying to clear the comment from within the response. I'm seeking assistance in figuring out how to resolve this problem.

app.controller('CommentController', function($scope, $http) {   
    $scope.addReview = function(obj) {
        this.comment.id = obj.id;

        $http.post('/save', this.comment).
          then(function(response) {
              obj.comments.push(response.data);
              this.comment = {};
          }, function(response) {

          });

    };

});

Answer №1

The reason for this behavior is related to the scope: 'this' specifically refers to the 'then' callback function in this context. Here's a suggested solution:

app.controller('CommentController', function($scope, $http) {
    $scope.addReview = function(obj) {
        // Save a reference to the current scope
        var self = this;
        this.comment.id = obj.id;

        $http.post('/save', this.comment).
            then(function(response) {
                obj.comments.push(response.data);
                // Use the previously saved scope reference
                self.comment = {};
            }, function(response) {

            });

    };

});

In addition, you may want to consider using the $scope.$apply function.

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

When I try to run Parcel, my ReactJS website just won't deploy in a serverless environment

For a while now, I've been working on a website using serverless. Everything was going smoothly until this morning when I encountered an issue with pushing updates from my site to the serverless platform. When trying to push, I received the following ...

vee-validate remains consistent in its language settings

Having trouble changing the error message in vee-validate, any suggestions on how to fix this? import VeeValidate from "vee-validate"; import hebrew from "vee-validate/dist/locale/he"; Vue.use(VeeValidate, { locale: "he", dictionary: { he: { me ...

I noticed that my Angular routes are prefixed with a '#%2F' before the specified URL in my app.js file

My Angular routes are set up in the app.js file like this: .config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl', controllerAs ...

Implement a click event for the X-Axis label in Angular 2 Highcharts

I'm currently facing a challenge with hand-rolling a solution that involves adding a click listener to an X-Axis label in a column chart using the HighCharts API within an Angular 2+ application. Here is what I have gathered so far: I am utilizing ...

Struggle encountered while incorporating PayPal into my project

Recently, I encountered an issue while trying to integrate the PayPal-node-SDK into my project for a Pay with PayPal option. The error message I received was: XMLHttpRequest cannot load https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&a ...

I am facing an issue with ThreeJs where my objects are not getting rendered after being added to a

After refactoring some code, I encountered an issue where nothing was being displayed. Surprisingly, there were no errors in the console to guide me towards a solution. The code in question is supposed to generate the same output as a previously functionin ...

Unable to activate tab in angular-ui

I encountered an angular error: Error: l is not a function .compile/</<@http://localhost/investui/app/vendor/uibootstrap/ui-bootstrap-tpls-0.4.0.min.js:1 Scope.prototype.$digest@http://localhost/investui/app/lib/angular.js:8811 Scope.prototype.$appl ...

Is it possible for a visitor to view every file on my website?

As a newcomer to web development, I am currently working on a website utilizing Node.js and express. The challenge I am facing is ensuring the security of sensitive information stored in certain files, such as payment codes, on the server side. Despite my ...

Encountering a login issue with the jsonwebtoken code, specifically getting the error message "something went wrong logging in TypeError: Cannot read properties of undefined (reading 'sign')."

I encountered an error in my console saying, "something went wrong logging in TypeError: Cannot read properties of undefined (reading 'sign')." I am seeking assistance in resolving this issue. Below is the code snippet: import { mAdmin } from &q ...

Uploading files with the help of Formik and the Material-UI stepper component

When attempting to upload a file, the entire component refreshes each time. The process involves 3 steps: the first step captures the user's name, the second step collects their address, and the third step allows them to upload a profile picture. Howe ...

Guide on displaying a grid in the center of the screen with a vertical sliding feature

I've noticed certain apps displaying a grid view or form on an alert box with vertical sliding, but I'm clueless about how to make it happen. As far as I know, this can be achieved using jQuery.. Any assistance would be greatly appreciated. Th ...

Issue with the dropdown functionality in an Angular reactive form

I am experiencing an issue with a select dropdown in my Angular project. I have implemented a reactive form, but the dropdown is not functioning as expected and I am unsure of how to resolve this issue. Could someone offer assistance or guidance on how to ...

What is the best way to prevent an element from reaching the border of the screen?

As a JavaScript beginner, I am working on creating a simple game. My objective is to prevent the player (20px x 20px) box from causing the screen to scroll. I want a fixed screen where the player cannot go beyond the edges of the screen. Below are my previ ...

Declaring a Javascript variable within an if statement does not alter the value of the global variable

Currently, I am working on enhancing my HTML projects by using JavaScript to modify the video source. Below is the video element in question. <div> <video id="songVid" onmouseover="controlsVid()"> <source src=&qu ...

Issues with displaying charts have been reported for generator-angular-fullstack and angular-chart.js

After working with Angular for some time, I decided to give Yeoman and generator-angular-fullstack a try. My main goal was to use angular-chart.js to display a chart in a particular view called poll.html. Surprisingly, everything loaded correctly except fo ...

initial cookie value not established in angular js

I need help passing a cookie value from one UI to another page. The specific cookie value I want to retrieve is the user's username, for example: Nithya When I log in to the home page, the cookie value appears empty until I refresh the page. Is the ...

Attaching a pre-Ajax .load event handler to a DOM element for execution

I am in the process of developing a website that utilizes SWFUpload and extensive use of Ajax $('#maincontent').load(URL) to dynamically update the main view content. However, I have encountered an issue in IE 7+ where if there is an SWFUpload i ...

Modifying CSS files in real-time

I've been attempting to dynamically change the CSS file, but I've run into an issue: Whenever I try to alter the style, it seems to work correctly while in "debug mode", showing that the changes are applied. However, once the JavaScript function ...

Unable to get Mongoose's Required field to work in conjunction with Enum validation

Encountering issues with Mongoose Required true and Enum validation when using updateone await MonthlyTarget.updateOne({website: req.body.website, year: req.body.year, month: req.body.month}, req.body, {upsert: true}); Model 'use strict'; import ...

Center the title vertically APEXCHARTS

I created this chart using Apex charts https://i.sstatic.net/j34Wc.png However, I am facing an issue where the 'Chart' title and caption are not properly aligned. The title should align with the graph horizontally, and the caption vertically. ...