Search code examples
angularjsxmlhttprequest

AngularJs update data after adding new record


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


Solution

  • 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>