0

Which is the best way to update comments data when new record is added to database? i recently have this code which is working fine , but I am thinking that this way of coding may take long time if i have large amount of comments.Any help is appreciated

function addComment(comment){
    dataservice.addComment(comment).then(function(response){
        if(response.status == 200){
            vm.getArticleComments(); // this will make new request to backend to fetch all comments
            comment.body = '';
        }else{
            return false;
        }
    });
 }

I was thinking to push new comment to view if response code is 200

2
  • if i were you i would push the new comment in the view when the response status is 200. There is no need to get all the comments and send that request Commented Sep 25, 2016 at 17:36
  • @Akis Yes that is what i did Commented Sep 25, 2016 at 17:51

1 Answer 1

1

IMO, Better use arrays instead.

Use unshift() method to prepend the ng-repeat list.

var data = [bar,bar2,bar3];
data.unshift(newItem);
//data = [newItem,bar,bar2,bar3];

Before doing this, make sure that you've successfully populated the database using $http.

As you said that you're think to push, that is also a good option but that will push the new data to the end of the list in the view.

Hope this helps you :)

var app = angular.module('app', []);

app.controller('MainCtrl', ['$scope', function ($scope) {
  $scope.items = [{
    name: '1',
    type: 'A'
  }, {
    name: '2',
    type: 'B'
  }];
  
  $scope.prependItem = function () {
    $scope.items.unshift({
      name: '3',
      type: 'C'
    });
  };
}]);
<!DOCTYPE html>
<html ng-app="app">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" />
    <script>document.write('<base href="' + document.location + '" />');</script>
    <script src="//code.angularjs.org/1.2.6/angular.min.js"></script>
    <script src="//code.angularjs.org/1.2.6/angular-route.min.js"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <div ng-repeat="item in items" watch-scope="item">
        <div class="someClass">Item name: {{item.name}}</div>
        <div class="anotherClass">Item type: {{item.type}}</div>
    </div>
    
    <button ng-click="prependItem()">Add New</button>
  </body>

</html>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for help ! unshift method did exactly what i wanted

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.