Peter Boomsma Peter Boomsma - 1 year ago 99
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


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


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

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 Source

ng-click should call this function

$scope.toggleDisplay = function(index){
    if(index == $scope.model.displayedIndex)
        $scope.model.displayedIndex = -1;  
        $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>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download