Bolboa Bolboa - 3 months ago 9
AngularJS Question

how to use $index to toggle click event of elements within the same element

I am using

ng-repeat
to display a multidimensional array...

<div class="form-container" ng-repeat="formblock in forms">
<div ng-click="showResults($index)" ng-if="repeat == true" class="drop" type="button">{{ formblock[0].form_name }}</div>
<div ng-hide="results[$index]" class="form-block" ng-repeat="form in formblock">
<div class="optionWrap">
<div class="formURL">{{ form.url }}</div>
<div class="formCount">{{ form.count }}</div>
<div class="formSubmit">{{ form.submit }}</div>
</div>
</div>
</div>


So what the code above does is display many lists, and the title of each list is
{formblock[0].form_name}
. When this title is clicked, I want to toggle the display of each
formblock
, but I want to keep the title visible.

The code above does not work right, when clicked, only a component of
formblock
is hidden, that is
form
is hidden. Moreover, it hides it for all lists, where I want the
ng-click
to only toggle the elements within the same container as the function.

How can I achieve this?

this is my controller function for
ng-click


$scope.showResults = function (idx) {
$scope.results[idx] = !$scope.results[idx];
}

Answer

You can pass the item of the ng-repeat to a function. Eg:

<div ng-repeat"item in list">
    <a href ng-click="doSomethingWith( item )">...</a>
</div>

$scope.doSomethingWith = function ( item ) {
    console.log('Fabulous! I received:', item);
};

In your specific case:

<div class="form-container" ng-repeat="formblock in forms">
    <div ng-click="showResults( formblock )" ng-if="repeat == true" class="drop" type="button">{{ formblock[0].form_name }}</div>
    <div ng-hide="! formblock.showResults " class="form-block" ng-repeat="form in formblock">
        ...
    </div>
</div>

$scope.showResults = function ( formBlock ) {
    formBlock.showResults = true;
};