Within my application, there is an array of objects structured as follows:
[{"ID":1, "parentID":0, "name":"Parent #1"},
{"ID":2, "parentID":0, "name":"Parent #2"},
{"ID":3, "parentID":1, "name":"Child #1 1"},
{"ID":4, "parentID":3, "name":"child #1 2"},
{"ID":5, "parentID":2, "name":"child #2 1"},
{"ID":6, "parentID":5, "name":"child #2 2"}]
I am looking to create a select menu that allows users to choose a leaf node while displaying the non-selectable parent nodes to show the hierarchy.
I have experimented with various approaches and found some success using the following template in Angular:
<div ng-repeat="(idx, category) in $scope.allCats">
<select ng-model="$scope.cats[idx]"
ng-options="cat as cat.name group by $scope.parentName(cat.parentID, idx) for cat in $scope.allCategories track by cat.ID">
<option value="">Select A Category</option>
</select>
</div>
The $scope.allCats
array contains the data mentioned above, and the $scope.parentName()
method returns a string.
However, I encountered issues where parent items displayed twice - once as an option and once as an optgroup. Additionally, the structure did not maintain the correct family tree relationships.
https://i.sstatic.net/PlYSj.png
How can I adjust my data or Angular template to achieve the desired behavior? Specifically, I want to display the entire hierarchy based on the parentID
attributes, ensuring each family shares a common ancestor and displaying parent items only once.
The complexity arises from having multiple levels of descendants and wanting to keep the solution general.