Emil Gurbanov Emil Gurbanov - 2 months ago 13
AngularJS Question

Show Element Based On Current Selected Menu Item Withing Ng-Repeat in Angular

I have a navigation bar in an application where I want to show related to a selected nav item image on click. Both navigation items and images located in the same array of objects in controller, however I cannot figure out how to achieve what I want. Could you please review the code below and navigate me to a suitable solution?

HTML

<ul id="nav-items">
<li ng-repeat="n in coreCtrl.navItems">{{n.title}}</li>
</ul>

<ul id="backgrounds">
<li ng-repeat="i in coreCtrl.navItems" ng-show"some-expression">
<img ng-src="{{i.bgUrl}}" />
</li>
</ul>


ANGULAR CTRL

self.navItems = [
{ title: 'item1', bgUrl: 'img1.jpg' }
, { title: 'item2', bgUrl: 'img2.jpg' }
, { title: 'item3', bgUrl: 'img3.jpg' }
, { title: 'item4', bgUrl: 'img4.jpg' }
, { title: 'item5', bgUrl: 'img5.jpg' }
];

Answer

Alright, first we need to to make change when clicking the title. So let's add a ng-click

<ul id="nav-items">
  <li ng-repeat="n in coreCtrl.navItems" 
      ng-click="coreCtrl.selectedItem=n">{{n.title}}</li>
</ul>

Then we display the image if the item is the selectedItem.

<ul id="backgrounds">
    <li ng-repeat="i in coreCtrl.navItems" ng-show"i===coreCtrl.selectedItem">
        <img ng-src="{{i.bgUrl}}" />
    </li>
</ul>

// Set default selected item in your controller.
self.selectedItem = self.navItems[0];

Another very common pattern in this situation is adding an active-class to your menu-item:

<ul id="nav-items">
  <li ng-repeat="n in coreCtrl.navItems" 
      ng-click="coreCtrl.selectedItem=n"
      ng-class="{'active':coreCtrl.selectedItem===n}">
    {{n.title}}
  </li>
</ul>