Updating data in AngularJS after inserting a new record

What is the most efficient method to update comments data when a new record is added to the database? I currently have this code that works well, but I am concerned that it may be slow if there are a large number of comments. Any assistance would be greatly 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'm considering adding the new comment to the view if the response code is 200

Answer №1

In my opinion, using arrays is a better option.

To prepend the list generated by ng-repeat, you can use the unshift() method.

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

Before proceeding with this approach, ensure that you have successfully populated the database using $http.

Although you mentioned considering pushing, it will add the new data to the end of the list in the view.

Hopefully, this explanation assists 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Accessing data outside of the scope when looping through items in Angular forEach

I am currently working on retrieving the Game ID generated by the APIService.postData method for the game. The goal is to utilize this Game ID within the Angular foreach loops to maintain foreign key constraints on the RESTful side. Any advice on extracti ...

Guide to displaying a unique custom modal popup when angular page is reloaded

Upon clicking the refresh button on the browser, a personalized popup should appear for confirmation. By utilizing @HostListener('window:beforeunload', ['$event']), it is possible to monitor the event; however, replacing the JavaScript ...

Angular's routeProvider is only able to detect routes specified with #/foo, rather than #!/foo. It prefers the hash symbol over

My application is functioning properly with routes like: when('/people/new', { templateUrl: 'partials/person-detail.html', controller: 'PersonDetailCtrl' }). when('/people/:id', { templateUrl: 'partials/person- ...

Steps for opening a clicked link in a new tab:

I have a link on my page that I would like to open in a new tab when clicked, but it doesn't seem to be working. Can anyone offer some suggestions or help? So far, I've tried the following code: <a target="_BLANK" ng-href="{{news.url ...

How can you customize the $stateProvider Provider in AngularJS?

This particular type of decorator is designed to work specifically with services and factories. However, I found it disappointing that it did not function as expected with providers. In an attempt to decorate the ui-router's $stateProvider, I tried th ...

What is the most effective method to implement an isLoggedIn function in AngularJS that is accessible from any controller or template?

I'm looking to create an isLoggedIn() function that can be accessed by both controllers and templates. Templates need this function to execute something like ng-show="isLoggedIn()". What would be the most efficient way to achieve this? If using a ser ...

Is it possible to integrate a backbone model with Angular?

Below is an example of a Backbone post model: var Post = Backbone.AssociatedModel.extend({ urlRoot: ApiService.resolveRESTUrl('posts'), defaults: { age : 0, fname : "", lname : "", manager : null }, ...

Improve page loading speed by removing JavaScript and CSS that block rendering of above-the-fold content, specifically focusing on Angular JS

Currently, I am working on improving the page speed of my MEAN stack application. My main challenge lies in eliminating render-blocking Javascript and CSS to enhance the loading time. Despite making significant progress, I have hit a roadblock with the con ...

How can I convert a list of checkboxes, generated by ng-repeat, into multiple columns?

Here is the HTML code snippet: <div class="checkbox"> <label> <input type="checkbox" ng-model="selectedAll.value" ng-click="checkAll()" />Check All </label> </div> <div class="checkbox" ng-repeat="carType i ...

Effective Pagination in Rails 5: Retrieving Total Entries with will_paginate and Active Model Serializers

I have implemented pagination using will_paginate and api-pagination for managing data, along with active_model_serializers to serialize the JSON. My goal is to send the total number of entries of the resource to the client side where AngularJS is being ut ...

Utilizing AngularJS: Employing the $q Promise Feature to Await Data Readiness in this Scenario

I am currently facing an issue with my Controller and Factory. The Controller initiates an API call in the Factory, but I am struggling to make it wait for the data to be gathered before proceeding. This is where I believe implementing something like $q mi ...

Implementing a for loop with the $http.get function followed by the .then

Previously in Angular, I utilized .success in conjunction with $http.get... Within the .success, I could execute the following: $http.get('/Home/GetUser') .success(function (result) { $scope.users = result; if (result != null) { ...

Preventing Sorting on a Single Item in an AngularJS ui-sortable List

Check out a Plunker example. [updated the plunk based on below answers] Updated Plunk I'm wondering how to disable sorting on specific items, such as item 1 and item 3, so the user cannot move those two items. I attempted to achieve this by using: ...

Leveraging AngularJS for parent-child communication through bindings in a unique and effective manner

I've come across the following code snippet: <div class="parent"> <div class="child"> and I have two directives, one for parent and one for child. When an event (such as a click) occurs on parent, I want something to happen on child ...

In Angular Typeahead, the model is used as an identifier and the Text represents the name in the array object

I'm currently utilizing the Angular UI Typeahead directive available at this link. Can someone provide guidance on how to assign a model as an id and display text as a name in it? I have attempted the method below but encountered issues. Any suggestio ...

Encountered an issue with Angular and RequireJS: The controller argument is not recognized as a function,

Currently, I am in the process of integrating angular with requirejs. Below is a snippet from my index.html file: <!DOCTYPE html> <html> <head> <script data-main="/js/app.js" src="/bower_components/requirejs/require.js"> ...

Unable to insert a JSON object into an Array

This might appear to be a duplicate, but it's not. None of the solutions I've tried have worked. Within my angular module, I have a list: this.checkedInterviews = [] Followed by a function that does the following: var interviewModel = { ...

Utilizing ng-grid to pass variables within cellTemplate

My ng-grid is connected to a SharePoint list, but I'm facing an issue where the list returns an ID number instead of the user name when populating a field with a user name. To solve this issue, I have created a function that converts the ID to a user ...

What is the best way to establish a global constant that can be accessed by multiple controllers in AngularJS?

Imagine I need to create a constant variable that can be shared between controllers in Angularjs; $webroot = "localhost/webroot/app" After some research, it appears that services are the recommended approach. But which one should I use? Should I implemen ...

AngularJS Directives Directory: A hub for all things related to

Can you recommend any websites or resources where I can find angularjs directives that have been created by the community? Just to clarify, I'm not looking for the ones that come built-in with angularjs. ...