Search code examples
angularjsangularjs-ng-clickng-class

ng-click / ng-class combination not working as expected with $index


For some reason my ng-click / ng-class combination is not working. On click the class 'hide' has to be added based on the equality of the productDisplay variable.

            <div ng-repeat="product in project.data track by $index">

                <p ng-click="productDisplay = $index"><strong>{{product.name}}</strong></p>

                <div class="fileList" ng-class="{'hide': productDisplay !== $index}">{{$index}}</div>

I can click on the <p> element and the div fileList will open but i can't close them once they are opened.

Any ideas?

thx,


Solution

  • Try toggling instead of going for $index, use productDisplay = !productDisplay this will change the ng-class expression and apply hide class whenever it gets clicked, or more better code you can use ng-if/ng-show/ng-hide instead of using ng-class.

    HTML

    <div ng-repeat="product in project.data track by $index">
    
        <p ng-click="productDisplay = !productDisplay"><strong>{{product.name}}</strong></p>
    
        <div class="fileList" ng-class="{'hide': productDisplay">{{$index}}</div>
    </div>
    

    Update

    Same thing can be done by maintaining productDisplay variable in parent scope of ng-repeat then you need to $parent.productDisplay inside ng-repeat

    <div ng-repeat="product in project.data track by $index">
    
        <p ng-click="$parent.productDisplay = $index"><strong>{{product.name}}</strong></p>
    
        <div class="fileList" ng-class="{'hide': $parent.productDisplay !== $index">{{$index}}</div>
    </div>
    

    Thanks.