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.