Bolboa Bolboa - 1 year ago 78
AngularJS Question

ng-click to affect only the element it is inside

I am using ng-repeat to generate some elements...

<div class="form-block" ng-repeat="form in formblock | filter:dateFilter">

<div ng-click="showResults()" ng-if="repeat == true" class="drop">{{ form.form_name }} <span class="caret"></span></div>

<div ng-show="results" class="formURL">{{ form.url }}</div>
<div ng-show="results" class="formCount">{{ form.count }}</div>
<div ng-show="results" class="formSubmit">{{ form.submit }}</div>


As you can see,
toggles the display of the other elements. The problem is, I only want the
to toggle the elements inside the same container, not toggle all elements.

In short, I only want the click event to affect the elements in the same container that the function is called, how can I do this?

this is
in my controller...

$scope.showResults = function(){
return ($scope.results ? $scope.results=false : $scope.results=true)

Ven Ven
Answer Source

ng-repeat provides you with a special variable (unless you already have an identfier): $index.

Using this, you can store (instead of a single boolean value) an object $index => toggleState in your angular code:

$scope.hiddenHeroes = {};

$scope.toggleHero = function (idx) {
    $scope.hiddenHeroes[idx] = !$scope.hiddenHeroes[idx];

And in your HTML:

<div ng-repeat="hero in heroes">
  <div class="hero" ng-hide="hiddenHeroes[$index]">
  All you want to know about {{hero}}!
  <br />
  <a ng-click="toggleHero($index)">Toggle {{hero}}</a>

See it live on!