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

Material-UI web application experiencing crashes due to worn-out cards, resulting in element type being declared as invalid and raising an error

After reviewing numerous similar SO questions, it appears that the issue always comes down to problems with imports. Typically, these involve mistyped import destinations or missing braces, but I have double-checked and found no such issues in my code. Th ...

Ensure that Javascript waits for the image to be fully loaded before triggering the Ajax function

function addResource() { var imgIndex = getIndexByImageID(currentDraggedImgID); var newImageID = resourceCollectionSize.length; // Insert the image $('#thePage').append('<img alt="Large" id="image' + newImageID + &a ...

Change the output of Object.fromEntries

I've been working on updating the values of an object using the .fromEntries() method. The issue I am facing is that even though I am returning a modified Array of hours, when the function completes it reverts back to the original complete Array. If ...

Step-by-step guide on implementing virtual scroll feature with ngFor Directive in Ionic 2

I am working on a project where I need to repeat a card multiple times using ngFor. Since the number of cards will vary each time the page loads, I want to use virtual scrolling to handle any potential overflow. However, I have been struggling to get it ...

Showing real-time information from an object

I am attempting to showcase the 'helpText' data on the front end based on the type. Is it feasible to include a conditional statement (metricsType variable) and the [key] value into what I want to return? The final 'p' below provides an ...

Exploring the Intersection of Windows 8 Store Applications and jQuery: Leveraging MSApp.execUnsafeLocalFunction

Developing a Windows 8 JavaScript Store App (using Cordova) has led to some complications when using jQuery. It seems that in order to utilize certain functions, I have had to modify the jQuery library by adding: MSApp.execUnsafeLocalFunction While this ...

Ionic app on mobile device experiencing issue with Autocomplete feature not filtering correctly in Angular

I am facing an issue with my autocomplete form. It works perfectly fine locally, but once compiled to a PWA, the data filtering feature stops functioning properly. The API is returning a JSON array response as expected. var modify = function (term) ...

Error: An unexpected identifier was encountered while executing my function

I've been trying to implement a function that I found online, but when I try to run it in the terminal, I keep getting this error: /home/simone/gekko/strategies/high.js:10 sma: function(name, price, points) ^^^ SyntaxError: Unexpected identifier I ...

How to toggle the display of a div by its id using index in Javascript

Currently, I am encountering a problem with toggling the div containers. When I click on the video button, I want the other divs to close if they are already open. However, due to the toggling mechanism, if a div is closed and I click on the corresponding ...

Customize the MUI (JoyUI) Autocomplete feature in React using react-hook-form to display a unique value instead of the label

Currently, I am in the process of creating a form that includes JoyUI (material) autocomplete and react-hook-form functionality. The array of objects I am using for my options looks like this: [ { label: "Todo", param: "TODO" }, ...

The JWT Cookie has successfully surfaced within the application tab and is now being transmitted in the request

When sending a JWT token to an authorized user in Express, the following code is used: The cookie-parser module is utilized. module.exports.getUser = async (req, res, next) => { console.log('i am in getuser'); const { SIT } = req.query; ...

Encountering difficulties linking to a stylesheet or a script in an HTML file delivered by Express server

Currently, I'm facing the challenge of breaking down my Express app code into multiple files. Unfortunately, I am unable to utilize <link href> or <script src> for linking stylesheets or scripts. Below is the relevant snippet from my inde ...

JavaScript code that opens a URL in a new tab with proper formatting

I'm having trouble figuring out how to make my JavaScript open a URL in a new tab. Here is the script: function viewSource(){ var webcache = "http://webcache.googleusercontent.com/search?q=cache:"; var request = "&prmd=ivn&strip=0& ...

Sending an array from the server to the client using Node and Express during page loading?

I am utilizing Node and Express in my project. The application fetches data from a remote database on page load and sends it to a handlebars template server-side. However, I would like this JSON data to also be accessible for client-side interactions. How ...

IframeResizer.js is automatically readjusting its position to the top left corner (0,0) when a javascript event or

Within our internal web environment, I have implemented IframeResizer.js in a rather basic manner. The child page contains a table generated by a third-party application with mouseover/hidden and javascript tags associated with the TH elements (including a ...

Is there a way to set an antd checkbox as checked even when its value is falsy within an antd formItem?

I'm currently looking to "invert" the behavior of the antd checkbox component. I am seeking to have the checkbox unchecked when the value/initialValue of the antD formItem is false. Below is my existing code: <FormItem label="Include skills list ...

Changing a "boolean bit array" to a numerical value using Typescript

Asking for help with converting a "boolean bit array" to a number: const array: boolean[] = [false, true, false, true]; // 0101 Any ideas on how to achieve the number 5 from this? Appreciate any suggestions. Thanks! ...

Customizing CSS for displayed MDBootrap components

I am currently using MDBoostrap, a styling tool similar to Bootstrap, in my React application. I have a select element that is coded like so: <div> <select id="Regions" style={errorSelect} value={this.state.userRegionId} onChange={this.handle ...

When accessing the defaultValue property of a select element, it will result in

Here is a typical HTML dropdown menu: <select name="email" id="email"> <option value="2" selected="selected">Before redirecting to PayPal</option> <option value="1">After payment is successful</option> <opti ...

How to Populate Object Literal with Multiple Objects in AngularJS

When I click on "Evan", I receive the following response: {"id":1,"name":"Evan"} If I click on "Robert", I will get: {"id":2,"name":"Robert"} Is there a way to modify this code so that it follows the aforementioned steps and generates an object similar ...