Peter Boomsma Peter Boomsma - 4 months ago 18
AngularJS Question

ng-click toggle with double statements

I have an ng-repeat that shows a list of movies, in each repeat is an icon that when clicked sets the current index to

model.displayedIndex
:

<span><i ng-click="toggle($index); model.displayedIndex = $index"></i></span>


And

<div class="additional_info" ng-show="$index === model.displayedIndex">
{{movie.overview}}
</div>>


When the icon is clicked the ng-show checks if the
$index === model.displayedIndex
if the value is the same the statement is true and the div is shown. This way only the ng-show inside the ng-repeat is true.

But now I'm looking for a way to toggle the ng-show when clicked on the same icon. Now nothing happens since the value model.displayedIndex is equal to index. How would I set the ng-show to false in this case?

I've tried adding the following to my icon:

<span><i ng-click="toggle($index); model.displayedIndex = $index ; toggleInfo = !toggleInfo"></i></span>


And in my div:

<div class="additional_info" ng-show="$index === model.displayedIndex || toggleInfo">


But obviously the model.displayedIndex is still equal to the index so the ng-show is still set to true.

Answer

ng-click should call this function

$scope.toggleDisplay = function(index){
    if(index == $scope.model.displayedIndex)
        $scope.model.displayedIndex = -1;  
    else
        $scope.model.displayedIndex = index;
}

If you click on the current displayedIndex - it will set it to -1 and then the ng-show condition will be false

Here is your span updated

<span><i ng-click="toggle($index); toggleDisplay($index)"></i></span>