Currently, I am working on building a sorting list using AngularJS. The goal is to have the data updated in the DOM dynamically when a user clicks on the name of a value. I am attempting to order the values by categories such as Bracelets, Charms, Earrings, and so on. Below is an example of how I could achieve this:
$scope.sortOptions = ['Bracelets','Charms', 'Earrings', ...]; // providing sorting options
$scope.sort = 'Bracelets'; // setting a default sortby item
$scope.active = function(x) {
return x === $scope.sort ? 'active' : '';
};
$scope.setSort = function(type){
$scope.sort = type.toLowerCase();
};
However, this method only works for a single object. In reality, I will need to handle multiple objects retrieved from the server.
Below is an example of my Category object structure:
{
"Pandora": {
"id": "1",
"s1": {
"d1": "Bracelets",
"d2": "Charms",
"d3": "Earrings",
"d4": "Jewelry",
"d5": "Necklaces",
"d6": "Pendants",
"d7": "Rings"
}
}
}
I have come across limitations with using AngularJS orderby without an array of objects, as discussed on StackOverFlow. To work around this, in my controller, I initialize $scope.catData = [];
and then populate it with data fetched from the server through a factory.
dataFactory.getCat().then(function(res){
$scope.catData = res.data;
});
Here is a snippet of what my HTML code looks like:
<li ng-repeat="(key, value) in catData">
<a href="#" data-id='{{value.id}}' class="anchor">{{key}}</a>
<ul class="sub" ng-class="{true: 'activeSlideF'}[value.id == 1]" >
<span ng-repeat="hi in value.s1 | orderBy:'hi':true">
<li>
<a href="#"><i class="fa fa-arrow-right"></i>{{hi}}</a>
</li>
</span>
</ul>
</li>
I suspect that when I assign $scope.catData = res.data
, existing data might be overwritten. While a quick solution could be $scope.catData = [res.data]
, I am not sure if this is the ideal approach. Any insights or suggestions would be greatly appreciated!
Thank you for your assistance!