Architecting Angular for an efficient sorting directive

As a newcomer to Angular, I am exploring the best approach to accomplish a simple task.

My goal is to update the order of a Project model in a database using the Angular $resource service.

Here is my template structure:

<table class="table table-hover">
    <thead>
        <tr>
            <th>#</th>
            <th>Title</th>
            <th>Date</th>
            <th>Link</th>
            <th></th>
            <th></th>
        </tr>
    </thead>
    <tbody id="sortable" my-drag-list>
        <tr ng-repeat="project in projects" ng-class="{warning: !project.publish}">
            <td></td>
            <td>{{project.title}}</td>
            <td>{{project.date|date: 'MMMM yyyy'}}</td>
            <td><a ng-href="{{project.link}}" target="blank">{{project.link}}</a></td>
            <td><a ng-href="#/projects/{{project.id}}/"><span class="glyphicon glyphicon-edit"></span></a></td>
            <td><a ng-click="deleteProject(project)"><span class="glyphicon glyphicon-trash"></span></a></td>
        </tr>
    </tbody>
</table>
<button type="button" class="btn btn-success" ng-show="data.saveSort" my-update-sort-button>Save new sort</button>

The tr elements in my tbody are draggable. When I click on the button (outside the scope of ng-repeat), I want to update the database with new position values based on the DOM positions of each tr element (lower position for upper trs).

Initially, I plan to create a my-update-sort-button directive as follows:

var link = function(scope, el){

    el.on('click', function(){
        var els = el.parent().find('tr');

        for(var i = 0, len = els.length; i<len; i++){
            Projects.update({id: els.eq(i).data('projectId')}, {position: i});
        }
    });
};

However, I have doubts about the effectiveness of this solution. I am hesitant about adding a data-project-id attribute to my tr elements.

I appreciate any ideas or alternative solutions for this scenario!

Answer №1

It is essential to maintain information about the position of each "project" within its model. Whenever a "project" is relocated, ensure that this information is updated in the respective model. This should be implemented within the "my-drag-list".

Upon clicking the update button, transmit data directly from the model without traversing through the DOM:

var link = function(scope, el){

  el.on('click', function(){
      var model;
      for(var i = 0, len = scope.model.projects.length; i<len; i++){
          model = scope.model.projects[i];
          Projects.update({id: model .id}, {position: model.position});
      }
  });
};

To optimize efficiency, aim to minimize server requests by consolidating all relevant information into a single transmission.

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

What is the best way to keep classes added through jQuery even after retrieving all the data from the API?

I'm trying to maintain the "active" class in the nav-link when a tab is clicked, but the issue arises when fetching data from an API (using node) as it refreshes the page. Despite my research efforts, I have been unable to find a solution. Any assista ...

Performing a Protractor test on an Angular 5 application

We're in the process of transitioning our ui-library from AngularJS to Angular 5. I'm encountering challenges with the protractor tests. I need guidance on how to update the old AngularJS test to align it with Angular 5. If anyone has dealt wit ...

Determine the size of a JSON object without converting it into a string

Is there a method to determine the size of a JSON object in megabytes without converting it into a string? I am aware of using JSON.parse(data).length to calculate the size in bytes, but parsing large data sets is time-consuming and not ideal for my need ...

Troubleshooting: Issue with Chrome's CSV Export Functionality in JavaScript/AngularJS

Currently, I am troubleshooting an issue with exporting a CSV file from a data table on a web application. The export functionality works fine on all browsers except for Chrome when the export button is clicked. I have been trying to solve this problem for ...

How can I toggle the visibility of a div based on whether a variable is defined or not?

How can I display a specific div on my webpage only when certain variables in PHP pull out a specific result from a database? I attempted to use the code snippet below, but it's not working as expected. Can someone provide guidance on how to achieve ...

ThreeJS Loading Page

Just starting out with ThreeJS and currently in the process of building a 3D Configurator. I'm looking to add a loading screen before the obj object loads, here's my current code: <!DOCTYPE html> </style> </head> <body& ...

What could be the reason for submitting the form while a new window is already open?

Hey there, I have a Javascript function that opens a new window and populates a field in the parent window based on the selected value. The issue I'm facing is that when the new window opens, the form is submitted without attaching the validation part ...

What is the best way to send a form value to a servlet?

As someone who is relatively new to programming, I kindly ask for your patience with me. I am currently attempting to extract values from a form (embedded in a JSP) using JavaScript, and then make a post request to a servlet. The form consists of 6 differ ...

Unable to implement the hover property for the entire class in CSS

I am struggling to highlight the entire class element on hover. Even though I have specified the button class as a selector, only the background color of the anchor tag is changing when I hover over the button. What could be causing this issue and how can ...

I'm looking to efficiently convert JSON or GeoJSON data into a Backbone model and then seamlessly transition that model into a Leaflet layer. Can anyone provide guidance on

As I work on refining layer definitions that can be added individually to a collection, my goal is to smoothly render the view or add them to a L.LayerGroup using the leaflet api. However, being new to JavaScript, I am uncertain about how to map the proper ...

Cleaning up objects from memory in JavaScript following an AJAX request

I am developing a web application with dynamic content loading. In my code, I have a main container div (<div id="container"/>) where I use AJAX to load HTML content. // function overwritten by loadMenu functions // called before loading a new sect ...

The Meteor Call object stands apart from the Meteor Method object that was received

When I send an object from the client to the server using a Meteor Call and Meteor method, something strange happens. The object is received in the Method but it looks different - nested within the giftList. Meteor Call - JSON.stringify {"personName& ...

Steps for generating an array entry containing an ObjectId and a Number

I am a newbie when it comes to mongodb and I am attempting to create an entry like this: { "resources": [ { "amount": 1, "resource": { "_id": "61be82b9549b4ede ...

Limit certain characters within special characters

I have experimented with a regular expression that matches strings containing zero or more occurrences of "%" and "&", but returns false if "@" or "$" is found: ^((%&)*(?!@).)*$ Now, I require a regex pattern to validate strings that must contain ...

Trying to modify the chosen option while filtering an ajax source using select2?

I am currently integrating the select2 library within a Bootstrap 4 modal in the following manner: <div class="form-group" id="fg-jbInd"> <label for="jbIndustry" class="control-label"gt;Industry * <sele ...

jQuery or AngularJS: The Best Choice for Large-Scale Projects?

I'm facing a decision for my upcoming major project that involves JavaScript. I am torn between jQuery and AngularJS, as my project will include interactions with Facebook and Google+. jQuery is known for its simplicity while AngularJS offers MVC capa ...

TinyMCE Node Replacement Feature

I am working on a WordPress plugin that adds a button to the TinyMCE editor. The intended behavior when the button is clicked is as follows: 1. If the selected text is not part of a shortcode (or is the shortcode itself), then the shortcode should be inser ...

Can you describe the characteristics of emissive materials in three.js?

Currently, I'm delving into a basic demo using three.js and finding myself perplexed by the way THREE.MeshPhongMaterial behaves, especially since I come from a background working with the Unity Game Engine. create_ring() { // creates a ring mesh ...

Implement input validation in React by enhancing the functionality of HTML input tags

Below is the input provided: const REGEX_EMAIL_VALIDATION = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}&bsol ...

Validation in AngularJS is limited to only accepting integers with the use of the

Can you help me with validating positive integer numbers using the ng-pattern attribute? Currently, I have this pattern: ^[0-9]{1,7}(\.[0-9]+)?$/, but it also allows decimal values. I want to restrict it to only accept whole numbers. ...