oderfla
oderfla

Reputation: 1797

Toggle Ionic list with sublist

I have this html:

<div class="list">
        <div ng-repeat="category in categories">
            <div class="item  item-icon-right">
                {{category.name}}
                <i class="icon icon-accessory ion-chevron-right pull-right"></i>
            </div>
            <div class="item" ng-repeat="sub_category in category.sub_categories">
                {{sub_category.name}}
            </div>
        </div>
</div>

And this javascript:

var data = {};
data.categories = [];
data.categories[0] = {
    id: 1
    ,name: "Computer"
    ,sub_categories: [
        {id:1,name:"Mac"}
        ,{id:2,name:"PC"}
    ]
};
data.categories[1] = {
    id: 2
    ,name: "Mobile"
    ,sub_categories: [
        {id:3,name:"Iphone"}
        ,{id:4,name:"Samsung"}
    ]
}
$scope.categories = data.categories;    

Right now a list with both cateogry and subcategories shows up.

I need the subcategories to be hidden by default. And only show when the parent is clicked. I also need the icon for the parent to change from ion-chevron-right to ion-chevron-down.

How can you do this with pure angular code? I could probably do this with jquery but I would prefer to have an angular approach.

Do I need to have the categories and subcategories to have their unique ID in order to access it? Or there is another smarter way to do this?

Upvotes: 0

Views: 901

Answers (1)

Pravin Erande
Pravin Erande

Reputation: 89

See HTML

<div class="list">
    <div ng-repeat="category in categories">
        <div class="item  item-icon-right">
            {{category.name}}
            <i class="icon icon-accessory ion-chevron-right pull-right" ng-click="showSubcategory($index)"></i>
        </div>
    </div>
    <div ng-if="sub_categories.length">
        <div ng-repeat="sub in sub_categories">{{sub.name}}</div>
    </div>
</div>

See scripting controller

$scope.sub_categories=[];
$scope.showSubcategory=function(index){
  $scope.sub_categories=[]; 
  $scope.sub_categories=data.categories[index].sub_categories;
}

Actually there are many ways, you can find as many as go on.

Upvotes: 1

Related Questions