Implementing the sorting feature in Angular JS to properly align sub sections with their correct parent sections

I'm facing an issue with the functionality of my sample code. Users can add sections and subsections within those sections, which are sortable using ui-sortable. However, after sorting the items, if I try to add a new sub-section to Section 2, it wrongly adds the item under Section 1 instead of Section 2.

You can see the demo here: Complete Code

My main question is how can I ensure that a new sub-section is added to the correct parent section after sorting them. Currently, the behavior is incorrect as the sub-section gets assigned to the wrong parent section.

This is a snippet of my HTML:

<ul ui-sortable="sortableOptions" ng-model="section" class="list">
   <li ng-repeat="parent in section">
       <span>Section {{parent.id}}</span>
       <ul ui-sortable="sortableOptions" ng-model="subSection" class="list">
          <ol ng-repeat="child in subSection" ng-if="child.parentId == parent.id">
               <span>SubSection {{child.id}}</span>
          </ol>
          <button ng-click="addSubSection($index + 1)">Add SubSection</button>
      </ul>
   </li>
</ul>

<button ng-click="addSection()">Add Section</button>

And this is my JS code:

var myApp = angular.module('myApp',['ui.sortable'])

.controller('MyCtrl', ['$scope', function($scope) {
   $scope.section    = [{id: 1}, {id:2}];
   $scope.subSection = [{id:1, parentId: 1}, {id:2, parentId: 1}, {id:3, parentId: 2}];

   $scope.addSection =function(){
      var newId = $scope.section.length +1;

      $scope.section.push({id: newId});
   };

   $scope.addSubSection = function(parentIndex) {
      var newSubId = $scope.subSection.length + 1;
      $scope.subSection.push({id:newSubId, parentId:parentIndex});
   };
}]);

I hope that clarifies my issue. Thank you.

Answer №1

The $index value may not be reliable for some reason (details below). To address this issue, a functional solution is suggested:

  1. Revise the addSubSection() function to accept the parent object instead of the index:

    $scope.addSubSection = function(parent) {
        var newSubId = $scope.subSection.length + 1;
        $scope.subSection.push({id:newSubId, parentId:parent.id});
    };
    
  2. Include the parent parameter in the template:

    <button ng-click="addSubSection(parent)">Add SubSection</button>
    

For a modified version, refer to this Plunker example: https://plnkr.co/edit/BFR6JLngJiFztR5P6dWa?p=preview


An issue arises with the inner sortable functionality when rearranging subsections. The current model organization, where all subsections exist in a single array and are visually grouped under a parent using ng-if, may be causing errors. Consider segregating subsections into separate arrays based on sections, like incorporating them within the scope of ng-repeat or nesting subsections within their respective section models, such as

$scope.section = [{id: 1, subSections: [...]}, {id:2, subSections: [...]}];
.

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

The jQuery library triggers an error that can only be resolved by refreshing the

I am currently experiencing an issue with my form (form links are provided below, specifically referring to form1). The problem arises when I include jquery.js, as it fails to load the doAjax and getIP functions that are contained in a separate js file nam ...

System for Node.js execution replay logging

Running a straightforward script that performs various tasks can be tedious when trying to debug errors. The log messages scattered throughout the code clutter the file, requiring more and more console.log entries for detailed information. Instead of fill ...

Tips for integrating the AJAX response into a Sumo Select dropdown menu

I am currently using Sumoselect for my dropdowns, which can be found at . The dropdowns on my page are named as countries, state, and cities. The countries are shown in the dropdown, and based on the country selected, the corresponding state name should a ...

How can we get ToUpperCase to function properly in this particular instance?

I am working on an input field in my project where I need to prevent users from entering certain words that are already present (without considering case sensitivity) in a JSON object called "tickets". One approach I attempted was: var value = val.toUppe ...

Website API: decouple backend and frontend functionality through an API

I am currently working on the development of a website and an app created through Cordova. The app will essentially mirror the functionalities of the website. The website is already established and heavily relies on JavaScript, with potential considerati ...

How can I use a button to save all changes made in a JqGrid checkbox column simultaneously?

In my jqgrid, there is a column named 'asistencia' which displays data from a database as checkboxes. These checkboxes are pre-checked based on the property formatoptions: {disabled : false}. I would like to implement a 'save' button th ...

Animating the Bookmark Star with CSS: A Step-by-Step Guide

I found this interesting piece of code: let animation = document.getElementById('fave'); animation.addEventListener('click', function() { $(animation).toggleClass('animate'); }); .fave { width: 70px; height: 50px; p ...

Encountering a glitch while iterating through function results in failure after the initial modification

I am facing some errors with the script provided below: var sections = ["#general_info", "#address_records", "#employment_history", "#driver_experience", "#military_experience", "#eeo_survey", &qu ...

Changes to attributes of an HTML tag cannot be made by jQuery code during an AJAX call

Could someone help me figure out why this jQuery code is not functioning properly? I have already tested it outside the $(document).ready block with no success. Note: The unusual "{{ }}" and "{% %}" syntax is typically used in Django. jQuery $(document) ...

Retrieve JSON data from Form Submission

While I am not a front end developer, I have been trying my hand at it recently. I hope that the community here can assist me with an issue I am facing. I have a form that is supposed to send files to a server-side API like shown below: <form id="uploa ...

What could be causing the JSON.stringify() replacer function to fail?

Here is the code snippet I'm working with: http://jsfiddle.net/8tAyu/7/ var data = { "foundation": "Mozilla", "model": "box", "week": 45, "transport": { "week": 3 }, "month": 7 }; console.log(JSON.stringify(data, ...

Center the text vertically within a card using Vuetify styling

I am seeking a way to vertically align text within a card using Vuetify or traditional CSS in a Vue project. Here is my code: <template> <div> <v-container class="my-5"> <v-row justify="space-between"> <v- ...

Troubleshooting CORS Problem with AWS CloudFront Signed Cookies

I encountered an issue while implementing cloudfront signed cookies. When trying to access '' from '', the CORS policy blocked it due to absence of the 'Access-Control-Allow-Origin' header. This problem arose after rest ...

Ensuring AngularJS Form Validation: Linking input to model even in the presence of input errors

When utilizing a form with angularjs form validation and ng-messages, the following code is used: <div class="form-group" ng-class="{ 'has-error': form1.firstName.$invalid && form1.firstName.$touched }"> <label class="control-la ...

Validating JSON against a JSON schema using JavaScript

My current task involves validating approximately 100 JSON Objects against a specific JSON schema to ensure that all fields and their types align with the schema requirements. Initially, I attempted to use a JSON schema generated from a website. However, ...

Exploring and cycling through numerous links using Selenium WebDriver in a node.js environment

Decided to switch from Casper.js to Selenium for access to more tools. Currently trying to loop through multiple links and navigate them using node.js along with selenium-webdriver. Struggling to find any helpful documentation or examples, as I keep enco ...

I am looking for a way to generate unique dynamic IDs for each input textbox created within a PHP while loop. Can

How can I retrieve the ID of a selected text box generated within a while loop in order to update a field similar to phpMyAdmin? <?php while($row=mysql_fetch_assoc($result)) { ?> <tr> <td><input type ...

group array by month and year

I have an array structured like this var dataset = [[1411151400000,1686],[1428604200000,1686],[1411151400000,1686]....] The goal is to group the data based on months and calculate the total sum of values for each month. The expected final output should ...

Ways to change attributes of deeply embedded objects?

Imagine having a complex object with nested properties like this: const obj = { Visualization: { Lower: [{ name: "Part", selectedValue: "60-000" }], Upper: [{ name: "Part", selectedValue: "60-000" }], ...

What is the best way to modify the height of a div before fetching an image using Ajax, and then revert it back to its original height once the image has been

Using a form and Ajax, I'm dynamically pulling an image to replace another image in the .results div. Initially, when the image was removed and loaded, the page jumped up and down, so I tried adding a style attribute to set the div height and then rem ...