proFX
proFX

Reputation: 71

AngularJS- How to handle each button created by ng-repeat

I am new to AngularJS. I have created <li> to which I used ng-repeat.

<li> contains images and buttons like like, comment and share which is inside <li> and created by ng-repeat.

I have made function which will replace empty like button to filled like button (By changing background image of button). But problem is this trigger applies to only first like button and other buttons does not change.

How can I fix this?

Code: HTML:

<html>
<body>
<ul>
<li ng-repeat="media in images"><div class="imgsub">
     <label class="usrlabel">Username</label>
       <div class="imagedb">
         <input type="hidden" value="{{media.id}}">
         <img ng-src="{{ media.imgurl }}" alt="Your photos"/>
        </div>
        <!-- <br><hr width="50%"> -->
         <div class="desc">
          <p>{{media.alt}}</p>
           <input type="button" class="likebutton" id="likeb" ng-click="like(media.id)" ng-dblclick="dislike(media .id)"/>
           <input type="button" class="commentbutton"/>
           <input type="button" class="sharebutton"/>
          </div>
        </div>  <br>
   </li><br><br><br>

</ul>
</body>
</html>

JS:

$scope.like = function(imgid)
    {
        document.
        getElementById("likeb").
        style.backgroundImage = "url(src/assets/like-filled.png)";
        alert(imgid);
    }

$scope.dislike = function(imgid)
{
    document.
    getElementById("likeb").
    style.backgroundImage = "url(src/assets/like-empty.png)";
}

Thanks for help & suggestions :)

Upvotes: 0

Views: 1041

Answers (2)

Rajat
Rajat

Reputation: 692

The id for each button should be unique but in your case, it's the same for all buttons ('likeb'). You can set the value of the attribute 'id' for each button dynamically by using '$index' and passing '$index' to the functions as follows:

<input type="button" class="likebutton" id="{{$index}}" ng-click="like($index)" ng-dblclick="dislike($index)"/>

Then in your controller, you can use the functions with the passed value. For example,

$scope.like = function(index)
    {
        document.
        getElementById(index).
        style.backgroundImage = "url(src/assets/like-filled.png)";
    }

Another good alternative in your case would be to use the directive ngClass.

Upvotes: 1

Koushik Chatterjee
Koushik Chatterjee

Reputation: 4175

use 2 css class for styling liked and disliked state, and then put the class conditionally with ng-class instead of DOM handling. and if you really want to perform a DOM operation (I will not recommend) then you can pass $event and style $event.currentTarget in order to perform some operation on that DOM object.

Upvotes: 0

Related Questions