javascript - Show html elements based on object property in Angular JS -
this code showing simple drop down list
var products = [ { "id": 1, "name": "product 1", "price": 2200, "category": "c1" }, { "id": 1, "name": "product 2", "price": 2200, "category": "c2" }, { "id": 1, "name": "product 3", "price": 2200, "category": "c1" }, { "id": 1, "name": "product 4", "price": 2200, "category": "c3" }, { "id": 1, "name": "product 5", "price": 2200, "category": "c3" } ]; <div ng-repeat="product in products" class="dropdown"> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">select <span class="caret"></span></button> <ul class="dropdown-menu"> <li ng-repeat="product in products"><a href="#">{{product.name}}</a></li> </ul> </div>
i want show drop down list based on category, if there 3 categories in object want 3 drop down list products showing inside drop down list if 2 category 2 drop down lists , on.
can me how achieve this? new angular.
thank
the tip in comments other question helpful.
you mentioned library $scope.categories = $filter('groupby')($scope.products, 'category')
in controller or ng-repeat="(group, cat) in ( products | groupby : 'category')"
in markup.
please have @ demo below or in fiddle.
angular.module('demoapp', ['ui.bootstrap', 'angular.filter']) .controller('maincontroller', function ($scope, $filter) { $scope.products = [{ "id": 1, "name": "product 1", "price": 2200, "category": "c1" }, { "id": 2, "name": "product 2", "price": 2200, "category": "c2" }, { "id": 3, "name": "product 3", "price": 2200, "category": "c1" }, { "id": 4, "name": "product 4", "price": 2200, "category": "c3" }, { "id": 5, "name": "product 5", "price": 2200, "category": "c3" }]; $scope.categories = $filter('groupby')($scope.products, 'category'); console.log($scope.categories); });
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.13.3/ui-bootstrap-tpls.js"></script> <script src="https://cdn.rawgit.com/a8m/angular-filter/master/dist/angular-filter.js"></script> <div ng-app="demoapp" ng-controller="maincontroller"> <div class="dropdown" dropdown> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown" dropdown-toggle>select products<span class="caret"></span> </button> <ul class="dropdown-menu"> <li ng-repeat="product in products"><a href="#">{{product.name}}</a></li> </ul> </div> <div dropdown> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown" dropdown-toggle>select category<span class="caret"></span> </button> <ul class="dropdown-menu"> <li ng-repeat="(group, cat) in categories"> <!--{{group}} {{cat}}--> <strong>category: {{group}}</strong> <a href="#" ng-repeat="item in cat">{{item.name}}</a> </li> </ul> </div> </div>
Comments
Post a Comment