Vitaly Menchikovsky
Vitaly Menchikovsky

Reputation: 8884

How to change icons on ng-repeat

I am trying to change icon when user select item on list.I manage to change the icon when click on the item, but the issue if user click on other item I want to change prev item to init state, like play music and pause.

my template:

  <div class="list">
        <a ng-repeat="item in items"
           class="item item-thumbnail-left item-button-right" ng-init="item.playing = false">
            <img ng-src="{{ item.user.avatar_url }}">
            <h2>{{ item.title }}</h2>
            <h4>{{ item.artist }}</h4>
            <button class="button button-positive" ng-click="selectItemToPlay(item);item.playing = !item.playing">
                <i class="{{item.playing == true && 'ion-pause' || 'ion-play'}}"></i>
            </button>
        </a>
    </div>

Upvotes: 1

Views: 1126

Answers (3)

Bharat
Bharat

Reputation: 943

You can track the selected item (say its itemId or $index) in one more variable. Say selectedItemId. This should be common for ng-repeat and not set initialized for each ng-repeat.

Set this variable on click of the item.

<button class="button button-positive" ng-click="selectItemToPlay(item);item.playing = !item.playing;selectedItemId=item.Id">

And set other items to init state if the selected item id is different from clicked one.

<i ng-class="{'ion-pause' : item.playing, 
            'ion-play' : !item.playing || selectedItemId !== item.id}"> </i>

//Together

<div class="list">
    <a ng-repeat="item in items"
       class="item item-thumbnail-left item-button-right" ng-init="item.playing = false">
        <img ng-src="{{ item.user.avatar_url }}">
        <h2>{{ item.title }}</h2>
        <h4>{{ item.artist }}</h4>
        <button class="button button-positive" ng-click="selectItemToPlay(item);item.playing = !item.playing;selectedItemId=item.Id">
            <i ng-class="{'ion-pause' : item.playing, 
            'ion-play' : !item.playing || selectedItemId !== item.id}"> </i>
        </button>
    </a>
</div>

Upvotes: 1

vinayakj
vinayakj

Reputation: 5681

 <i ng-class="{'ion-pause' : item.playing,
               'ion-play' : !item.playing}">
 </i>

Or

 <i ng-class="{item.playing ? 'ion-pause' : 'ion-play'}">
 </i>

Upvotes: 0

Christian Yang
Christian Yang

Reputation: 472

I think you're looking for the ngClass directive, which conditionally sets CSS classes based on an expression. For your code:

 <i ng-class="{'ion-pause': item.playing, 'ion-play': !item.playing}"></i>

Upvotes: 0

Related Questions