Ila
Ila

Reputation: 3538

AngularJS "accordion" loading & unloading DOM elements using ng-click

My page has several categories, with content stored in JSON files. On page load, the categories have no content. When the category heading is clicked, its contents are loaded. When it is clicked again, or another category is clicked, its contents should be removed.

On my current sketch (Plunkr) the loading of content on ng-click works, but all categories are populated with the content of the category clicked. I'm calling it like this:

  <div ng-controller="FoodCtrl">
    <h3 ng-click="loadFood('food1')">Food 1</h3>

       <div class="food origin">
              <food-list />
       </div>

    <h3 ng-click="loadFood('food2')">Food 2</h3>

          <div class="food origin">
               <food-list />
          </div>

  </div>

The problem as I can see it is that I am not limiting the scope of what is loaded into <food-list />, so both lists get the same content. How can I restructure this so that <food-list /> has a context of "current active category"? Would a "toggle" function (like this JSFiddle) work better for this?

Upvotes: 1

Views: 319

Answers (1)

Ila
Ila

Reputation: 3538

The novice AngularJS user discovers the magic of ng-show, using a a variable category that was already in my controller:

  <div ng-controller="FoodCtrl">
     <h3 ng-click="loadFood('food1')">Food 1</h3>

     <div class="food origin">
        <food-list ng-show="category == 'food1' "  />
     </div>

    <h3 ng-click="loadFood('food2')">Food 2</h3>

    <div class="food origin">
         <food-list  ng-show="category == 'food2' " />
    </div>

  </div>

Upvotes: 1

Related Questions