Getting the products in a loop through
$http.get
request is not a good idea, since it works on
asynchronos
reqest, the result which you get from the loop is not a valid for the particular category, since before executing the first
ajax call
the loop would have completed the iteration.
More over this will result in numerous request to the server which will reduce the performance of the system.
simple way to achieve the grouping is by
joining the data in the server and return as
json
to the browser and pass it to the
ng-repeat
as
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<div data-ng-repeat="catg in Categorys">
{{catg.ecom_category_title}}
<ul data-ng-repeat="prd in catg.Products">
<li>{{prd.ecom_product_title}}</li>
</ul>
</div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function ($scope, $http) {
var data = [{ ecom_category_title: 'cat1', Products: [{ ecom_product_title: 'cat1 prod 1' }, { ecom_product_title: 'cat1 prod 2' }] },
{ ecom_category_title: 'cat2', Products: [{ ecom_product_title: 'cat2 prod 1' }, { ecom_product_title: 'cat2 prod 2' }] },
{ ecom_category_title: 'cat3', Products: [{ ecom_product_title: 'cat3 prod 1' }, { ecom_product_title: 'cat3 prod 2' }] }]
$scope.Categorys = data;
});
</script>
</body>
</html>
Demo:
Plunker[
^]
Controller code to join the data
string[] categoryNames = { "aa", "bb" };
List<Category> lst = new List<Category>();
foreach (string cat in categoryNames)
lst.Add(new Category() { CategoryName = cat, Products = GetProducts(cat) });
return JSON(lst);
private static Product[] GetProducts(string cat)
{
return null;
}