Javascript 清除回调函数内部的数据

Javascript 清除回调函数内部的数据,javascript,angularjs,Javascript,Angularjs,我有以下代码片段。我试图澄清这一评论,但我无法在回应中做到这一点。有人能帮我弄清楚怎么做吗 app.controller('CommentController', function($scope, $http) { $scope.addReview = function(obj) { this.comment.id = obj.id; $http.post('/save', this.comment). then(functio

我有以下代码片段。我试图澄清这一评论,但我无法在回应中做到这一点。有人能帮我弄清楚怎么做吗

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

          });

    };

});

这是因为作用域:“this”指的是“then”回调。 试试这个:

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

          });

    };

});

此外,您可能会使用$scope.$apply函数。

可能的重复。您能解释一下apply函数吗?这是因为操作的异步性质:您从服务器获取数据并将其应用于您的作用域。如果角度摘要循环未同步,您将无法在视图上看到赋值结果。您可以使用$scope.$apply(fn)强制更新,但您应该首先进行评估,以了解您是否真的需要它。请看这里: