Вопрос

I have a controller which loads data via Restangular like so:

var oneTopic = Restangular.one('topics', topic.id);
oneTopic.get({}, {"Authorization" : localStorageService.get('***')}).then(function(topic) {
  topic.getList('comments', {}, {"Authorization" : localStorageService.get('***')}).then(function(comments){
    $scope.comments = comments;
    //console.log($scope.comments);
  });
});

And then a function which posts a new comment and one that deletes a comment.

    $scope.delComment = function(comment_id, author_id){
      var comment = Restangular.one('comments', comment_id);
      comment.remove({author_id: author_id}, {"Authorization" : localStorageService.get('***')}).then(function(){
        // need to perform refresh here
      });
    };

    $scope.postComment = function(mood) {
      $scope.commentData.mood = mood;
      comments.post($scope.commentData, {}, {"Authorization" : localStorageService.get('***')}).then(function(response){
        // need to perform refresh here
      }, function(response){
        $scope.error = response.data.message;
      })
    };

How would I refresh the comments scope without reloading the page? The data is being populated in the HTML with an

<div ng-repeat="comment in comments">
Это было полезно?

Решение

Modify the existing array referenced by $scope.comments and the data binding will take care of it.

For example:

$scope.delComment = function(comment_id, author_id) {
  var comment = Restangular.one('comments', comment_id);
  comment.remove({ author_id: author_id }, { "Authorization": localStorageService.get('***')
  }).then(function() {

    // Some remove-from-array implementation, for example:

    var c = $scope.comments; 

    for(var i = 0, l = c.length; i < l; i++) {
      if (c[i].comment_id === comment_id) {
          c = c.splice(i, 1);
          break;
      }
    }
  });
};
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top