0

After click on 'likeBtn', would like to set '.like-txt' to visible using angularJS scope. I would also like to change the counter at the '.like-txt' so that it reflects how many times have clicked on the 'likeBtn'.But the code in the script wouldn't do that.

<summary class="row book-component">
    <div  ng-repeat='x in books|orderBy:order' class="col-md-12 col-sm-12 col-xs-12" >
    <img ng-src={{x.url}} class="thumbnail-image" > 
    <div> 
       <h2 ng-bind="x.title" class="title"></h2>
       <h4 ng-bind="x.author" class="author" style="color:grey;"></h4> 
       <h5 class="like-txt" style="color:grey;visibility:hidden;"><span ng-bind="counter"></span> people liked this </h5> 
       <h5><span ng-click="like(this)" class="likeBtn">Like </span> </h5>
    </div>
</summary>

<script>    
  var counter=0;
  /* After click on 'likeBtn', would like to set '.like-txt' to visible using angularJS scope. But the code in the script wouldn't do that.   */
  var app2 = angular.module('form-input', []);
  app2.controller('ctrl', function($scope) { 
      $scope.like = function(that){ 
        counter++;   
        $scope.closest('div').find('.like-txt').css('visibility', 'visible');
      };
  }
  /*  Create JSON representations of the content */
    $scope.books=[
      {title:'Jani',author:'Norway', url:"images/beach.jpg"},
      {title:'Hege',author:'Sweden',url:"images/plane.jpg"}
    ];

1 Answer 1

1

This is how you should do it:

<div ng-show="counter > 0">{{counter}} people liked this</div>

$scope.counter = 0;

$scope.like = function(){
    $scope.counter++;
};

Use ng-show to control the visibility, and use {{}} to bind the scope value as it is more readable. Fiddle here


Update: In order to get this working for ng-repeat, I would keep a counter as part of each book. For example:

ng-click="like(book)"

<div ng-show="book.counter > 0">{{book.counter}} people like this</div>

$scope.like = function(book){
    book.counter = book.counter || 0; // if it hasn't been set, set it to zero
    book.counter++;
};

Updated fiddle here

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. It works but it is actually showing ' people liked this' shows on every ng-repeat item. can it be shown only once for the nearest .likeTxt
I have added the JSON representation of the contents.
Updated answer, and provided a newer fiddle. Just missed the ng-repeat on the first pass.
Thanks @Matt Way for the explanation!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.