0

I have the following code snippet. I'm trying to clear the comment, but I can't do it from within the response. Could someone help me to figure out how to do this.

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) {

          });

    };

});
Code Junkie
  • 7,602
  • 26
  • 79
  • 141
  • 1
    possible duplicate of [How to access the correct \`this\` / context inside a callback?](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) – James Thorpe Aug 07 '15 at 11:39

1 Answers1

2

it is because of the scope: 'this' is refering to the 'then' callback. Try this:

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

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

          });

    };

});

Moreover, you would probably use the $scope.$apply function.

pietro909
  • 1,811
  • 1
  • 19
  • 26
  • 1
    Could you explain the the apply function? – Code Junkie Aug 07 '15 at 11:57
  • It is because of the asyncronous nature of the operation: you are getting data from the server and apply it to your scope. If the angular digest loop is not synchronized you simply won't see the result of the assignment on the view. You can force that update using $scope.$apply(fn) but you should at first do an assessment in order to understand whether you really need it. Have a look here: http://www.sitepoint.com/understanding-angulars-apply-digest/ – pietro909 Aug 07 '15 at 12:53