javascript - How to implement groups in Angular.js -
i have 2 lists, 1 names of "groups" , names of "items". should change contents of list of items when group selected.
<div class="headers"> <div id="header-1">header 1</div> <div id="header-2 selected">header 2</div> </div> <div class="contents"> <div id="contents-2-1">Сontents 2.1</div> <div id="contents-2-2">Сontents 2.2</div> </div>
currently i've monkey-coded 2 controllers interacting via service, it's not angular-idiomatic way that.
it solvable if each #header-n
contained #contents-n-*
inside of it, scoping rules enough implement required behaviour. problem it's impossible so.
another way in angular todomvc example via list filtering. combined quantity of items on groups high enough discard option.
how implement such group selection in idiomatic way?
upd. data looking this:
var groups = [ { text: 'group 1', items: [1, 2, 3] }, ... ]; var items = [ { id: 1, text: 'item 1' }, ... ];
you should able make work - assuming have kind of $scope
var selected group (which object)
$scope.selectgroup = function(group) { $scope.selectedgroup = group; //lets group 1 $scope.groupitems = items.filter(function(item) { return $scope.selectedgroup.items.indexof(item.id) > -1; }); }
and html:
<div class="headers"> <div id="header-1" ng-class=" {'selected': selectedgroup.text == group.text }" ng-click="selectgroup(group)" ng-repeat="group in groups">{{group.text}}</div> </div> <div class="contents"> <div id="contents-2-1" ng-repeat="item in groupitems">{{item.text}}</div> </div>
demo: http://jsfiddle.net/hb7lu/15275/
(this assumes "groups" accessible repeat over)
Comments
Post a Comment