2015-12-15 113 views
0

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

<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

这是你应该怎么做:

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

$scope.counter = 0; 

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

使用ng-show控制的知名度,并使用{{}}的范围值绑定,因为它更具有可读性。小提琴here


更新:为了得到这个工作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++; 
}; 

更新小提琴here

+0

谢谢。它可以工作,但实际上在每个重复项目中都会显示'人们喜欢这个'节目。可以只显示一次最近的.likeTxt – user21

+0

我已经添加了内容的JSON表示。 – user21

+0

更新后的答案,并提供了一个新的小提琴。刚刚错过了第一遍的重复。 –