在 angularJS 范围内设置可见性

setting visibility in angularJS scope

点击 'likeBtn' 后,想使用 angularJS 范围将“.like-txt”设置为可见。我还想更改“.like-txt”处的计数器,以便它反映点击 'likeBtn' 的次数。但脚本中的代码不会这样做。

<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"}
    ];

您应该这样做:

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

$scope.counter = 0;

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

使用ng-show控制可见性,使用{{}}绑定范围值,更易读。 Fiddlehere


更新:为了让这个在 ng-repeat 上工作,我会在每本书中保留一个计数器。例如:

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++;
};

已更新 fiddle here